Wednesday, March 4, 2015

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: iterator
在弹栈的时候需要分情况一下:
1)如果当前栈顶元素的右结点存在并且还没访问过(也就是右结点不等于上一个访问结点),那么就把当前结点移到右结点继续循环;
2)如果栈顶元素右结点是空或者已经访问过,那么说明栈顶元素的左右子树都访问完毕,应该访问自己继续回溯了。
算法时间复杂度是O(n),空间复杂度是栈的大小O(logn).
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList postorderTraversal(TreeNode root) {
        ArrayList res = new ArrayList();
        if(root == null)
            return res;
        
        LinkedList stack = new LinkedList();
        TreeNode pre = null;
        
        while(root != null || !stack.isEmpty()) {
            if(root != null) {
                stack.push(root);
                root = root.left;
            }else {
                TreeNode peekNode = stack.peek();
                
                //如果右结点存在并且还没访问过,把当前结点移到右结点
                if(peekNode.right != null && pre != peekNode.right) {
                    root = peekNode.right;
                }else {
                    stack.pop();
                    res.add(peekNode.val);
                    pre = peekNode;
                }
            }
        }
        return res;
    }
}
Or
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List postorderTraversal(TreeNode root) {
        List result = new ArrayList();
        
        if(root == null) {
            return result;
        }
        
        TreeNode left;
        TreeNode right;
        Stack stack = new Stack();
        stack.push(root);
        
        while(!stack.isEmpty()) {
            TreeNode top = stack.peek();
            
            if(top.left == null && top.right == null) {
                result.add(top.val);
                stack.pop();
            }
            
            if(top.left != null) {
                stack.push(top.left);
                top.left = null;
                continue;
            }
            
            if(top.right != null) {
                stack.push(top.right);
                top.right = null;
                continue;
            }
        }
        return result;
    }
}

No comments:

Post a Comment