102. Binary Tree Level Order Traversal

Recursive

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        ArrayList<List<Integer>> res = new ArrayList<>();
        helper(root, 0, res);
        return res;
    }

    private void helper(TreeNode root, int height, List<List<Integer>> res) {
        if (root == null) {
            return;
        }
        // create a empty list if it doesn't exist
        if (res.size() <= height) {
            res.add(new ArrayList<>());
        }
        res.get(height).add(root.val);
        helper(root.left, height + 1, res);
        helper(root.right, height + 1, res);
    }
}

Iterative

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        ArrayList<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int height = 0;
        while (!queue.isEmpty()) {
            // creates a list for the current level
            res.add(new ArrayList<>());

            // adds all the element of this level to the list
            int queueLen = queue.size();
            for (int i = 0; i < queueLen; i++) {
                TreeNode node = queue.removeFirst();
                res.get(height).add(node.val);
                if (node.left != null) {
                    queue.addLast(node.left);
                }
                if (node.right != null) {
                    queue.addLast(node.right);
                }
            }

            // go to the next level
            height++;
        }

        return res;
    }
}