[LeetCode] Binary Tree Postorder Traversal

Given a binary tree, return the postorder traversal of its nodes' values.

For example: Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

 

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

虽然用递归微不足道,但看一下递归实现方法如下:

复制代码
struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };
 
class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> result;

        PostTraver(root,result);


        return result;
    }
private:
    void PostTraver(TreeNode *root,vector<int> &VecResult)
    {
      if(root!=NULL)
      {
          PostTraver(root->left,VecResult);
          PostTraver(root->right,VecResult);
          VecResult.push_back(root->val);
      }
    }
};
复制代码

用迭代的方法实现如下:

复制代码
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

typedef struct
{     

    TreeNode* ptr;   

    char tag; 

}stacknode;

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {

            vector<int> result;
        
            std::stack<stacknode> s;

            stacknode x;  

            TreeNode *p=root;   

            do 

            {   

                while (p!=NULL)    //遍历左子树  

                {     

                    x.ptr = p;     
                    x.tag =  'L' ;     //标记为左子树    

                    s.push(x);  
                    p=p->left;  

                }      

                while (!s.empty() && s.top().tag== 'R' )  

                {    

                    x = s.top(); 

                    s.pop();    

                    p = x.ptr;   

                    result.push_back(p->val) ;  //tag为R,表示右子树访问完毕,故访问根结点  

                } 

                if (!s.empty())   

                {    

                    s.top().tag ='R';   //遍历右子树  

                    p = s.top().ptr->right;      

                }  

            }while (!s.empty()); 


            return result;
        }
    };


    int main()
    {
        TreeNode *root = new TreeNode(1);
        TreeNode *r1 = new TreeNode(2);
        TreeNode *r2 = new TreeNode(3);
        root->left = r1;
        root->right = r2;
        r1->left = NULL;
        r1->right = NULL;
        r2->left = NULL;
        r2->right = NULL;
        Solution sol;
        vector<int> vec;
        vec = sol.postorderTraversal(root);
        for(vector<int>::iterator iter = vec.begin();iter!= vec.end();iter++)
        {
            cout<<*iter<<" ";

        }
        cout<<endl;

        return 0;
    }
复制代码

 

posted @   Xylophone  Views(151)  Comments(0Edit  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示