leetcode

Binary Tree Level Order Traversal

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:

Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

Iterator solution: use a queue to store TreeNode.

public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> results = new ArrayList<List<Integer>>();

        if (root==null) {
            return results;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        int currentLevelCount = 1;
        int nextLevelCount = 0;
        List<Integer> level = new ArrayList<Integer>();

        while (!queue.isEmpty()) {
            TreeNode currentNode = queue.poll();
            currentLevelCount = currentLevelCount - 1;
            level.add(currentNode.val);
            if (currentNode.left!=null) {
                queue.add(currentNode.left);
                nextLevelCount++;
            }

            if (currentNode.right!=null) {
                queue.add(currentNode.right);
                nextLevelCount++;
            }

            if (currentLevelCount==0) {
                currentLevelCount = nextLevelCount;
                nextLevelCount = 0;                
                results.add(new ArrayList<Integer>(level));
                level.clear();
            }    
        }

        return results;        
    }

Recursive solution: Recursively calculate the last level in the binary tree.

public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        if (root==null) {
            return results;
        }

        int height = height(root);

        for (int i=1; i<=height; i++) {
            List<Integer> result = levelOrder(root, i);
            results.add(result);
        }
        return results;
    }

    private List<Integer> levelOrder(TreeNode root, int level) {
        if (root==null) {
            return null;
        }
        List<Integer> result = new ArrayList<Integer>();
        if (level==1) {
            result.add(root.val);
        } else if (level>1){
            List<Integer> left = levelOrder(root.left, level-1);
            if (left!=null) {
                result.addAll(left);
            }
            List<Integer> right = levelOrder(root.right, level-1);
            if (right!=null) {
                result.addAll(right);
            }
        }

        return result;
    }

    private int height (TreeNode root) {
        if (root==null) {
            return 0;
        }

        return Math.max(height(root.left), height(root.right)) + 1;
    }