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?

答案

class Solution {

    public List postorderTraversal(TreeNode root) {
        List list = new ArrayList<>();
        Stack stk = new Stack<>();
        Map map = new HashMap<>();

        pushLeft(stk, map, root);

        while(!stk.isEmpty()) {
            TreeNode curr = stk.peek();
            Boolean is_right_visited = map.get(curr);
            if(is_right_visited) {
                list.add(stk.pop().val);
            }
            else {
                if(curr.right != null) {
                    pushLeft(stk, map, curr.right);
                }
                map.put(curr, true);
            }
        }
        return list;
    }

    public void pushLeft(Stack stk, Map map, TreeNode root) {
        while(root != null) {
            stk.push(root);
            map.put(root, false);
            root = root.left;
        }
    }   
}

你可能感兴趣的:(Binary Tree Postorder Traversal)