Binary Tree Postorder Traversal

 

 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           if(root == NULL)
15                 return res;
16           stack<TreeNode*> node;
17           node.push(root);
18           TreeNode* pre, *cur;
19           pre = root;
20           while(!node.empty())
21           {
22                cur = node.top();
23                if(cur->left == pre || cur->right == pre || (cur->left == NULL && cur->right == NULL))
24                {
25                     res.push_back(cur->val);
26                     node.pop();
27                     pre = cur;
28                }
29                else
30                {
31                    if(cur->right != NULL)
32                             node.push(cur->right);
33                    
34                    if(cur->left != NULL)
35                            node.push(cur->left);
36                }
37           }
38           return res;
39     }
40 };

 

posted on 2016-05-24 10:49  RenewDo  阅读(107)  评论(0编辑  收藏  举报

导航