lintcode 二叉树前序遍历

二叉树的前序遍历 
 

给出一棵二叉树,返回其节点值的前序遍历。

样例

给出一棵二叉树 {1,#,2,3},

   1
    \
     2
    /
   3

 返回 [1,2,3].

 1 /**
 2  * Definition of TreeNode:
 3  * class TreeNode {
 4  * public:
 5  *     int val;
 6  *     TreeNode *left, *right;
 7  *     TreeNode(int val) {
 8  *         this->val = val;
 9  *         this->left = this->right = NULL;
10  *     }
11  * }
12  */
13 
14 //递归
15 class Solution {
16 public:
17     /*
18      * @param root: A Tree
19      * @return: Preorder in ArrayList which contains node values.
20      */
21      
22      void inorder (TreeNode *root, vector<int> &result) {
23          result.push_back(root->val);
24          if (root->left != NULL) {
25              inorder(root->left, result);
26          }
27          
28          if (root->right != NULL) {
29              inorder(root->right, result);
30          }
31      }
32      
33     vector<int> preorderTraversal(TreeNode * root) {
34         // write your code here
35         vector<int> result;
36         if (root == NULL) {
37             return result;
38         }
39         inorder(root, result);
40         return result;
41     }
42 };

 

 

posted on 2017-08-18 18:53  狗剩的美丽家园  阅读(163)  评论(0编辑  收藏  举报

导航