leetcode:Binary Tree Postorder Traversal

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> res;
        stack<pair<TreeNode *,int>>s;
        TreeNode *p = root;
        while(p!=NULL||!s.empty())
        {
            while(p)
            {
                s.push(pair<TreeNode*,int>(p,1));
                p = p->left;
            }
            pair<TreeNode*,int> q = s.top();
            s.pop();
            if(q.second==1)
            {
                s.push(pair<TreeNode*,int>(q.first,2));
                p = q.first->right;
            }
            else
            {
                res.push_back(q.first->val);
                p = NULL;
            }
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode,C++,traversal)