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?

问题链接

cpp代码如下:

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        TreeNode *p=root,*r=NULL;
        stack<TreeNode*> sta;
        vector<int> ans;
        while(p||!sta.empty()){
            if(p){
                sta.push(p);
                p=p->left;
            }else{
                p=sta.top();
                if(p->right&&p->right!=r){
                    sta.push(p->right);
                    p=p->right->left;
                }else{
                    ans.push_back(p->val);
                    sta.pop();
                    r=p;
                    p=NULL;
                }
            }
        }
        return ans;
    }
};


猜你喜欢

转载自blog.csdn.net/wocaoqwerty/article/details/41773689