Binary Tree Postorder Traversal

Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
 
Note: Recursive solution is trivial, could you do it iteratively?
 
Solution: 1. Iterative way (stack). Time: O(n), Space: O(n).
2. Recursive solution. Time: O(n), Space: O(n).
3. Threaded tree (Morris). Time: O(n), Space: O(1).
You may refer to my blog for more detailed explanations:
http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html
 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> postorderTraversal(TreeNode *root) {
13         vector<int> res;
14         postorderTraversalRe(root, res);
15         return res;
16     }
17     
18     void postorderTraversalRe(TreeNode* root, vector<int> &res)
19     {
20         if(!root) return;
21         postorderTraversalRe(root->left, res);
22         postorderTraversalRe(root->right, res);
23         res.push_back(root->val);
24     }
25 };

 

posted @ 2014-04-15 11:06  beehard  阅读(175)  评论(0编辑  收藏  举报