Friday, February 7, 2014

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?

Solution:
Always think about stacks when we need to go back find a parent node. 
Post-order is: left-right-root. root is always traversed at last, so we can use a Array List, and insert all child nodes before the root node. 
Use a stack to save child elements. According to the sequence of Array List, we will pop out right child first, so we would push left child first. 



/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        ArrayList<Integer> ret = new ArrayList<Integer>();
        
        if(root == null) return ret;
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode node = stack.pop();
            if(node.left != null)
                stack.push(node.left);
            if(node.right != null)
                stack.push(node.right);
            ret.add(0,node.val);      // solution key
        }
        return ret;
    }
}

No comments:

Post a Comment