Binary Tree Postorder Traversal

Binary Tree Postorder Traversal

Total Accepted: 82814 Total Submissions: 244246 Difficulty: Hard

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?

 
/**
 * Definition for a binary tree node.
 * 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>                 res;
        stack<pair<TreeNode*,bool>> paths;
        TreeNode*                   p = root;
    
        while(p || !paths.empty()){
            while(p){
                paths.push(make_pair(p,false));
                p = p->left;
            }
            while(!paths.empty()){
                pair<TreeNode*,bool>& node = paths.top();
                if(node.second){
                    res.push_back(node.first->val);
                    paths.pop();
                }else{
                    p = node.first->right;
                    node.second = true;
                    break;
                }
            }
        }
        
        return res;
    }
};
posted @ 2015-12-18 10:28  zengzy  阅读(126)  评论(0编辑  收藏  举报
levels of contents