leetcode:Binary Tree Postorder Traversal

 1 class Solution{
 2 public:
 3     vector<int>postorderTraversal(TreeNode *root)
 4     {
 5         vector<int>postOrder;
 6         Traversal(root,postOrder);
 7         return postOrder;
 8     }
 9     stack<TreeNode*> st;
10 private:
11     void Traversal(TreeNode *root,vector<int>&postOrder)
12     {
13         if(root==NULL)
14             return;
15         TreeNode *p;
16         TreeNode *pre=NULL;
17         bool flag=true;
18         p=root;
19         while(p||!st.empty())
20         {
21             if(p)
22             {
23                 st.push(p);
24                 p=p->left;
25             }
26             else
27             {
28                 p=st.top();
29                 if(p->right==NULL||p->right==pre)
30                 {
31                     st.pop();
32                     postOrder.push_back(p->val);
33                     pre=p;
34                     p=NULL;
35                 }
36                 else
37                 {
38                     p=p->right;
39                 }
40             }
41         }
42 
43     }
44 };

 

posted @ 2014-07-01 13:16  dupuleng  阅读(100)  评论(0编辑  收藏  举报