LeetCode 145. Binary Tree Postorder Traversal

先自己在纸上画棵树,发现可以用stack实现迭代版的后序遍历,最开始先把root压入栈。另外维护一个栈,记录对应节点出栈的次数,如果是1,表明左右节点已输出,就输出;如果为0,说明左右节点还未压入栈,就把次数加1,且把左右节点压入栈。

 1 /**
 2  * Definition for a binary tree node.
 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         if(!root) return res;
15         stack<TreeNode*> stk;
16         stack<int> time;
17         stk.push(root);
18         time.push(0);
19         while(!stk.empty()){
20             TreeNode* top = stk.top();
21             int tmp = time.top(); 
22             if(tmp == 0){
23                 ++tmp; time.pop(); time.push(tmp);
24                 if(top->right) {stk.push(top->right);time.push(0);}
25                 if(top->left) {stk.push(top->left);time.push(0);}
26             }
27             else{
28                 res.push_back(top->val);
29                 stk.pop();time.pop();
30             }
31             
32         }
33         return res;
34     }
35 };

 

posted @ 2016-04-14 20:43  co0oder  阅读(120)  评论(0编辑  收藏  举报