2014年5月6日星期二

Binary Tree - Binary Tree Preorder Traversal

This idea is basically the same as the In Order… which take the else part, but Pre Order take the if part… The tough point is to observe by using examples.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if(root == null){
            return result;
        }
       // Queue<TreeNode> process = new LinkedList<TreeNode>();
        Stack<TreeNode> processing = new Stack<TreeNode>();
        TreeNode current = root;
        while(!processing.isEmpty() || current != null){
            if(current != null){
                result.add(current.val);
                processing.push(current);
                current = current.left;
            }else{
                current = processing.pop();
                current = current.right;
            }
        }
        // while(!process.isEmpty()){
        //     result.add(process.poll().val);
        // }
        return result;
    }
}

没有评论: