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

/**
 * 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) {
        List<Integer> result = new ArrayList<>();
        if (root == null) return result;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode runner = root;
        while (runner != null) {
            stack.push(runner);
            runner = runner.left;
        }
        // Use child to keep track of whether node have been visited.
        TreeNode child = null;
        while (!stack.isEmpty()) {
            TreeNode cur = stack.peek();
            // If no right child or right child has been visited
            if (cur.right == null || cur.right == child) {
                result.add(stack.pop().val);
                child = cur;
            } else {
                // Continue to push left child of the new node.
                cur = cur.right;
                while (cur != null) {
                    stack.push(cur);
                    cur = cur.left;
                }
            }
        }
        return result;
    }
}

reference:
http://rleetcode.blogspot.com/2014/06/binary-tree-postorder-traversal.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s