leetcode

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].

use two stacks, first stack to traverse the tree, second to track the results in the order of (M,R,L...)

Then pop the results from the second stack and print it out.

//LRM
public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> results = new ArrayList<Integer>();

        if (root==null) {
            return results;
        }

        Stack<TreeNode> child = new Stack<TreeNode>();
        Stack<TreeNode> parent = new Stack<TreeNode>();
        child.push(root);

        while(!child.isEmpty()) {
            TreeNode current = child.pop();
            parent.push(current);
            if (current.left!=null) {
                child.push(current.left);
            }
            if (current.right!=null) {
                child.push(current.right);
            }
        }

        while(!parent.isEmpty()) {
            TreeNode current = parent.pop();
            results.add(current.val);
        }

        return results;
    }