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?

解析:

如果采用递归方式来做,思路是很简单的。关键是返回值result的处理:因为不能在preorderTraversal中定义vector<int>,所以定义了临时函数,把result作为一个入口参数传入其中并进行操作。

 1 // recursive, but it's trivial...
 2 vector<int> preorderTraversal(TreeNode* root) {
 3     vector<int> v;
 4     preTraversal(root, v);
 5     return v;
 6 }
 7 void preTraversal(TreeNode* root, vector<int>& v){
 8     if(!root) return;
 9     v.push_back(root->val);
10     preTraversal(root->left, v);
11     preTraversal(root->right, v);
12 }

 

 

迭代,用栈

 1 vector<int> preorderTraversal(TreeNode* root) {
 2     vector<int> v;
 3     if(!root) return v;
 4     TreeNode* temp = root;
 5     stack<TreeNode*> s;
 6     s.push(root);
 7     while(!s.empty()){
 8         temp = s.top();
 9         s.pop();
10         v.push_back(temp->val);
11         if(temp->right) s.push(temp->right);
12         if(temp->left) s.push(temp->left);
13     }
14     return v;
15 }

 

其他方法

 1 vector<int> preorderTraversal(TreeNode* root) {
 2     vector<int> v;
 3     if(!root) return v;
 4     TreeNode* temp = root;
 5     stack<TreeNode*> s;
 6     while(true){
 7         while(temp){
 8             v.push_back(temp->val);
 9             if(temp->right) s.push(temp->right);
10             temp = temp->left;
11         }
12         if(s.empty()) break;
13         temp = s.top();
14         s.pop();
15     };
16 }
17 
18 // morris traversal, O(1) space
19 vector<int> preorderTraversal(TreeNode* root) {
20     vector<int> v;
21     if(!root) return v;
22     TreeNode* temp = root, *prev;
23     while(temp){
24         if(!temp->left){
25             v.push_back(temp->val);
26             temp = temp->right;
27         }else{
28             prev = temp->left;
29             while(prev->right&&(prev->right != temp))
30                 prev = prev->right;
31             if(!prev->right){
32                 v.push_back(temp->val);
33                 prev->right = temp;
34                 temp = temp->left;
35             }else{
36                 prev->right = NULL;
37                 temp = temp->right;
38             }
39         }
40     }
41 }

 

posted on 2015-11-06 09:50  已停更  阅读(214)  评论(0编辑  收藏  举报