Wednesday, June 11, 2014

Binary Tree Inorder Traversal (Iterately)

Not hard question. Basic idea is to use stack. Stack is a good tool for replacing loop with recursion. One thing should be aware of is "Be careful for different cases"

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
     
        ArrayList<Integer> rslt = new ArrayList<Integer>();
        if(root == null) return rslt;
        LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
     
        TreeNode tmpRoot = root;
        stack.push(tmpRoot);
        while(!stack.isEmpty()){
            while(tmpRoot.left != null){
                stack.push(tmpRoot.left);
                tmpRoot = tmpRoot.left;
            }
         
            TreeNode tmpNode = stack.pop();
         
            rslt.add(tmpNode.val);
            if(tmpNode.right != null){
                tmpRoot = tmpNode.right;
                stack.push(tmpRoot);
            }
            else{
                if(stack.isEmpty()) break;
                else{
                    tmpRoot = stack.peekFirst();
                    tmpRoot.left = null;
                }
            }
        }
        return rslt;
    }
}

No comments:

Post a Comment