Friday, July 24, 2015

Binary Tree Postorder Traversal | Leetcode

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?

---

Solution: Use a stack to hold the nodes. For each node we pop, check if this is a leaf node. If so, add its value to the answer list. If not, push a new fake leaf node with the popped node's value, push the right node, and then push the left node. This will simulate the postorder traversal.
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        if (root == null) return Collections.emptyList();
        
        List<Integer> answer = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        stack.add(root);
        
        do {
            TreeNode node = stack.pop();
            if (node.left == null && node.right == null) {
                answer.add(node.val);
                continue;
            }
            stack.push(new TreeNode(node.val));
            if (node.right != null) stack.push(node.right);
            if (node.left != null) stack.push(node.left);
        } while (!stack.isEmpty());
        
        return answer;
    }
}

No comments: