您的位置:首页 > 其它

[Leetcode 145, Hard] Binary Tree Postorder Traversal

2015-07-20 09:20 459 查看
Problem:

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?
Analysis:

Solutions:

C++:

vector<int> postorderTraversal(TreeNode* root) {
        vector<int> node_list;
        if(root == NULL)
            return node_list;
            
        TreeNode *p_cur = root;
        TreeNode *p_visited = NULL;
        stack<TreeNode *> node_stack;
        while(p_cur || !node_stack.empty()) {
            if(p_cur) {
                node_stack.push(p_cur);
                p_cur = p_cur->left;
            } else {
                p_cur = node_stack.top();
                
                if(p_cur->right == NULL || p_cur->right == p_visited) {
                    node_list.push_back(p_cur->val);
                    p_visited = p_cur;
                    node_stack.pop();
                    p_cur = NULL;
                } else
                    p_cur = p_cur->right;
            }
        }
        
        return node_list;
    }
Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: