码迷,mamicode.com
首页 > 其他好文 > 详细

145. Binary Tree Postorder Traversal (Stack, Tree)

时间:2015-10-03 18:13:25      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:

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?

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        vector<int> result;
        if(!root) return result;
        
        stack<MyNode*> treeStack;
        MyNode* myRoot = new MyNode(root);
        MyNode* current, *newNode;
        treeStack.push(myRoot);
      
        while(!treeStack.empty())
        {
            current = treeStack.top();
            treeStack.pop();
            if(!current->flag)
            {
                current->flag = true;
                treeStack.push(current);
                if(current->node->right) {
                    newNode = new MyNode(current->node->right);
                    treeStack.push(newNode);
                }
                if(current->node->left) {
                    newNode = new MyNode(current->node->left);
                    treeStack.push(newNode);
                }
            }
            else
            {
                result.push_back(current->node->val);
            }
        }
        return result;
        
    }
    struct MyNode
    {
        TreeNode* node;
        bool flag; //indicate if the node has been visited
        MyNode(TreeNode* x) : node(x),flag(false) {}
    };
};

 

145. Binary Tree Postorder Traversal (Stack, Tree)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4853632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!