Thursday, November 6, 2014

Facebook: Printing a binary tree L-R

Print a Binary Tree L-R
Binary Tree Level Order Traversal II

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        
        if (root == null) {
            return result;
        }
        
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> curList = new ArrayList<Integer>();
            
            for (int i = 0; i < size; i++) {
                TreeNode currNode = queue.poll();
                curList.add(currNode.val);
                
                if (currNode.left != null) {
                    queue.offer(currNode.left);
                }
                
                if (currNode.right != null) {
                    queue.offer(currNode.right);
                }
            }
            
            result.add(0, curList);
        }
        
        return result;       
    }
}

No comments:

Post a Comment