Binary Tree Level Order Traversal

List a binary tree's values one level at a time, from the top down and left to right.

Given the root of a binary tree, return its values level by level: first the root, then the nodes one step below it, then the nodes two steps below, and so on. Within each level, list the values from left to right, and put each level in its own list.

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]
Example 2
Input: root = [1]
Output: [[1]]
Example 3
Input: root = []
Output: []
Solution

The Idea

Think of a family tree read one generation at a time: first the grandparent, then all the children, then all the grandchildren. This problem asks for the same reading of a binary tree.

Example 1 writes its tree row by row, left to right, with null where a child is missing. At the top is 3, the root. Below it, 3 has a left child, 9, and a right child, 20. The two null values say that 9 has no children. Then 20 has two children, 15 and 7. Here 3 and 20 each have two children, the most any node in a binary tree may have.

A node's level is its row: 3 is on level 1, 9 and 20 on level 2, and 15 and 7 on level 3. So the answer is [[3], [9, 20], [15, 7]].

Reading the rows is easy for us on paper, but a program only holds the root and follows links from a node to its children. From 3 it can reach 9 and 20, and only from 20 can it reach 15 and 7. How does it visit the nodes row by row, and how does it know where one row stops and the next begins?

Picture a waiting line. Put 3 in it. Take 3 out, and put its children, 9 and 20, at the back. Take 9 out: it has no children. Take 20 out and put 15 and 7 at the back. Nodes leave the line in the order they joined, and the children of one row always join after that whole row. So the nodes come out row by row. A line that works this way, first in, first out, is called a queue.

Look at the picture below. On the left, the three levels of the tree sit in their own bands. Call each pass that takes one level out of the queue a round. On the right is what the queue holds at the start of each round.

The tree of Example 1 drawn in three levels: 3, then 9 and 20, then 15 and 7. Next to each level, the queue at the start of that round holds exactly that level: [3], then [9, 20], then [15, 7].

In the row labelled round 2, the queue holds 9 and 20, exactly the nodes of level 2, and its size is 2. That size tells the program where level 2 stops. When a round starts, the queue holds one whole level and nothing else. Take out exactly as many nodes as its size, and that round reads one level.

Visiting a tree this way, nearest nodes first and spreading out one row at a time, is called breadth-first search, or BFS for short.

Solution Approach

Turning that idea into code means settling four things: which queue class to use, how to mark the end of a level, which child goes in first, and what to do with an empty tree.

The queue

Which Java class gives us a waiting line? ArrayDeque from java.util does, used through the Queue interface. Its add puts a node at the back and its poll takes one from the front, both in constant time.

Where a level ends

How does the loop know when it has read a whole level? It reads the queue's size once, at the start of the round, and saves it in a variable. It then polls exactly that many nodes. The children it adds along the way wait at the back for the next round.

The saved number matters, because the queue's size keeps changing during the round: polling shrinks it and adding children grows it.

Left to right

How do the values of a level come out left to right? Each node adds its left child before its right child. Level 2 then holds 9 before 20, so their children follow in the same order on level 3.

The empty tree

What if there is no tree at all, as in Example 3? The root is then null, so it is added to the queue only when it exists. With an empty queue the loop never runs, and the answer is an empty list.

Java Solution

The method levelOrder works in these steps:

  1. First, create levels, the list of lists that will be returned, and queue, an ArrayDeque. Add root to the queue if it is not null.
  2. An outer while loop runs one round per level, for as long as the queue is not empty. At the start of each round, save the queue's size in size and create a new list, level, for this level's values.
  3. Inside, a for loop runs size times. Each time it polls a node, adds its value to level, and adds the node's left child and then its right child to the queue, skipping a missing child.
  4. After the for loop, add level to levels. Once the queue is empty, the method returns levels.

The class also has a small TreeNode class and a build helper that turns the row-by-row form of the examples into a tree. The main method runs the three examples, a tree that is one long branch, and a tree where every level is full.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class LevelOrderTraversal {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        if (root != null) {
            queue.add(root);
        }
        while (!queue.isEmpty()) {
            int size = queue.size();          // the queue holds exactly one level now
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);     // children join the back: the next level
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            levels.add(level);
        }
        return levels;
    }

    // Builds a tree from the row-by-row form, with null for a missing child.
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> parents = new ArrayDeque<>();
        parents.add(root);
        int k = 1;
        while (k < values.length) {
            TreeNode parent = parents.poll();
            if (values[k] != null) {
                parent.left = new TreeNode(values[k]);
                parents.add(parent.left);
            }
            k++;
            if (k < values.length && values[k] != null) {
                parent.right = new TreeNode(values[k]);
                parents.add(parent.right);
            }
            k++;
        }
        return root;
    }

    public static void main(String[] args) {
        System.out.println(levelOrder(build(3, 9, 20, null, null, 15, 7)));
        System.out.println(levelOrder(build(1)));
        System.out.println(levelOrder(build()));
        System.out.println(levelOrder(build(1, 2, null, 3, null, 4)));       // one long branch
        System.out.println(levelOrder(build(1, 2, 3, 4, 5, 6, 7)));          // every level full
    }
}

Running it prints:

Output
[[3], [9, 20], [15, 7]]
[[1]]
[]
[[1], [2], [3], [4]]
[[1], [2, 3], [4, 5, 6, 7]]

The top line, [[3], [9, 20], [15, 7]], is the tree from Example 1, read in three rounds. The bare [] on the third line comes from the empty tree, where the loop never runs. Look at the fourth line, [[1], [2], [3], [4]]. The tree [1, 2, null, 3, null, 4] has one node per level, each the left child of the one above, so every round polls a single node. The last line shows the other shape: each level holds twice as many nodes as the one above, ending with [4, 5, 6, 7].

Why save the size in size instead of writing the loop test as i < queue.size()? We ran Example 1 with that change. It printed [[3, 9], [20, 15], [7]]. In the first round, polling 3 and adding 9 and 20 grows the queue to two nodes, so the loop goes on and takes 9 as well. The levels get mixed.

Complexity

The work is one trip through the queue for every node in the tree.

  • Time: O(n), because each of the n nodes joins the queue once and leaves it once, and leaving costs only one value added to level and two child checks.
  • Space: O(w) besides the output, where w is the number of nodes on the widest level, because the queue holds at most one level plus the children added from it so far.

For a full tree like the last one in main, the bottom level holds about half of all the nodes, so w can be close to n/2. The same loop, with a small change to how each level is stored, solves Zigzag Level Order Traversal.