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?

不用递归吗?没问题,我们用LinkedList做,速度惊人。对于左子树,放入链表;对于右子树,直接移动nodenode = node.right。这样每次用addFirst()node放入结果数组的首位,再将root.right放入首位,每次再将root.right的左子树放入链表,当右子树遍历完后,再从链表中以FIFO的顺序取出从上到下的左子树结点,以相同方法放入首位。

Solution

Using LinkedList

public class Solution {
    public List<Integer> postorderTraversal(TreeNode node) {
        LinkedList<Integer> result = new LinkedList<Integer>();
        Stack<TreeNode> leftChildren = new Stack<TreeNode>();
        while(node != null) {
            result.addFirst(node.val);
            if (node.left != null) leftChildren.push(node.left);
            node = node.right;
            if (node == null && !leftChildren.isEmpty()) node = leftChildren.pop();
        }
        return result;
    }
}

Using Recursion

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList();
        if (root == null) return res;
        helper(root, res);
        return res;
    }
    public void helper(TreeNode root, ArrayList<Integer> res) {
        if (root.left != null) helper(root.left, res);
        if (root.right != null) helper(root.right, res);
        res.add(root.val);
    }
}

linspiration
161 声望53 粉丝