2014年5月9日星期五

Loop Solution - Binary Tree Level Order Traversal II

The idea is to use a queue to process each level, and when level size is zero, resize it to queue the size, and add the list to the result, head position.(instead of Stack...)


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
        if(root == null){
            return new ArrayList<ArrayList<Integer>>();
        }
        Queue<TreeNode> process = new LinkedList<TreeNode>();
        process.offer(root);
        int countLevel = 1;
        ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> curLevel = new ArrayList<Integer>();
        while(!process.isEmpty()){
            TreeNode cur = process.poll();
            curLevel.add(cur.val);
            countLevel--;
           
            if(cur.left != null){
                process.offer(cur.left);
            }
            if(cur.right != null){
                process.offer(cur.right);
            }
           
            if(countLevel == 0){
                results.add(0, curLevel);
                curLevel = new ArrayList<Integer>();
                countLevel = process.size();
            }
        }
        return results;
    }
}

没有评论: