Friday, November 7, 2014

Facebook: Print a tree in level order

http://buttercola.blogspot.com/2014/08/leetcode-binary-tree-level-order.html

Code (Java):
/**
 * 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>> levelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        
        levelOrder(root, result, 1);
        
        return result;
    }
    
    private void levelOrder(TreeNode node, ArrayList<ArrayList<Integer>> result, int level) {
        if (node == null) return;
        
        if (result.size() < level) {
            ArrayList<Integer> temp = new ArrayList<Integer>();
            temp.add(node.val);
            result.add(temp);
        } else {
            result.get(level - 1).add(node.val);
        }
        
        levelOrder(node.left, result, level + 1);
        levelOrder(node.right, result, level + 1);
    }
}

Discussion:
The time complexity is O(n) since we traverse all elements of the tree. The space complexity is O(logn) since the recursive preorder traversal.

Iterative Solution:
In the iterative solution, we use a queue. For each element traversed, we enqueue both its left child and right child. Then we enter into the next level and dequeue all the elements of the queue.

Code (Java):
/**
 * 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>> levelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (root == null) return result;
        
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            ArrayList<Integer> levelList = new ArrayList<Integer>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode curr = queue.poll();
                levelList.add(curr.val);
                if (curr.left != null) {
                    queue.offer(curr.left);
                }
                if (curr.right != null) {
                    queue.offer(curr.right);
                }
            }
            result.add(levelList);
        }
        return result;
    }
}

No comments:

Post a Comment