binary-tree-preorder-traversal——前序遍历

Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree{1,#,2,3},

   1
    \
     2
    /
   3

 

return[1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

 

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> preorderTraversal(TreeNode *root) {
13         if(root==NULL)
14             return v;
15         v.push_back(root->val);
16         preorderTraversal(root->left);
17         preorderTraversal(root->right);
18         return v;
19     }
20     vector<int> v;
21 };

非递归

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<int> preorderTraversal(TreeNode *root) {
13         vector<int> v;
14         if(root==NULL)
15             return v;
16         stack<TreeNode *> tree;
17         tree.push(root);
18         while(!tree.empty()){
19             TreeNode *p=tree.top();
20             v.push_back(p->val);
21             tree.pop();
22             if(p->right!=NULL)
23                 tree.push(p->right);
24             if(p->left!=NULL)
25                 tree.push(p->left);
26         }
27         return v;
28     }
29 };

 

posted @ 2017-06-07 17:03  鸭子船长  阅读(208)  评论(0编辑  收藏  举报