LC145 Binary Tree Postorder Traversal

这个题比前序遍历难在,当tmp等于NULL时,stack需要不断地弹出节点,直到检查到一个节点,它的右节点不为空而且还没有被遍历过。这个判断条件写出来还是比较难。

当然,另一种巧妙的做法是,用前序遍历(按右根左的顺序)来求得数组,然后把数组做一个翻转就行。

 1 class Solution {
 2 public:
 3     vector<int> postorderTraversal(TreeNode* root) {
 4         vector<int> result;
 5         if(root==NULL)
 6             return result;
 7         stack<TreeNode*> is;
 8         is.push(root);
 9         TreeNode* tmp = root->left;
10         TreeNode* pre=NULL;
11         while(!is.empty()||tmp!=NULL)
12         {
13             if(tmp)
14             {
15                 is.push(tmp);
16                 tmp=tmp->left;
17             }
18             else
19             {
20                 while(!is.empty()&&(is.top()->right==NULL||is.top()->right==tmp))
21                 {
22                     tmp=is.top();
23                     result.push_back(tmp->val);
24                     is.pop();
25                 }
26                 if(!is.empty())
27                     tmp=is.top()->right;
28                 else
29                     return result;        
30             }
31         }
32         return result;
33     }
34 };

 

posted @ 2016-07-28 09:35  vaevaevae  阅读(195)  评论(0编辑  收藏  举报