5/30/2014

38. Binary Tree Postorder Traversal

/**
 * 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) {
        ArrayList<Integer> res = new ArrayList<Integer> ();
        Stack<TreeNode> stack = new Stack();
     
        if (root==null) return res;
        stack.add(root);
        TreeNode previous = root;
     
        while(!stack.isEmpty()) {
            TreeNode current = stack.peek();
            if ((current.right==null && current.left==null) || current.left==previous || current.right==previous) {
                res.add(current.val);
                stack.pop();
                previous = current;
            } else {
                if (current.right!=null) stack.add(current.right);
                if (current.left!=null) stack.add(current.left);
            }
        }
     
        return res;
    }
}


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<Integer> ();
        postorder(root, res);
        return res;
    }
   
    public void postorder(TreeNode root, ArrayList<Integer> res) {
        if (root==null) return;
       
        postorder(root.left, res);
        postorder(root.right, res);
        res.add(root.val);
    }
}

2 条评论:

  1. 1. Stack.
    2. previous为之前pop的,current为现在的peek.
    3. if current is leaf or it has been searched (its left & right child has been popped), 把current放到res并pop,检查下一个peek.
    4. else push its right & left child.

    回复删除