Trees & BST · Pattern 3 of 12

Level order traversal: BFS one level at a time

Put the root in a queue. Each round, read the queue size, pop exactly that many nodes and push their children: those nodes are one level.

4 variations · 7 problems · 6 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Anything "per level" or "level by level"
  • Zigzag, reversed or bottom-up level order
  • Connect each node to its right neighbour
  • A check where the first missing node matters (is the tree complete?)

The template

Traversals
List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> res = new ArrayList<>();
    Deque<TreeNode> q = new ArrayDeque<>();
    if (root != null) q.offer(root);
    while (!q.isEmpty()) {
        int size = q.size();                            // the nodes of this level
        List<Integer> level = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            TreeNode node = q.poll();
            level.add(node.val);
            if (node.left != null) q.offer(node.left);
            if (node.right != null) q.offer(node.right);
        }
        res.add(level);
    }
    return res;
}

// complete tree: in BFS order, no real node may come after the first null
boolean isCompleteTree(TreeNode root) {
    Queue<TreeNode> q = new LinkedList<>();             // LinkedList accepts nulls
    q.offer(root);
    boolean seenNull = false;
    while (!q.isEmpty()) {
        TreeNode node = q.poll();
        if (node == null) { seenNull = true; continue; }
        if (seenNull) return false;
        q.offer(node.left);
        q.offer(node.right);
    }
    return true;
}

The variations

  1. 1Level by level

    The size of the queue at the start of a round is the size of the level. The same loop links each node to the next one on its level.

  2. 2Change the order of the levels

    Run the normal BFS. For zigzag, reverse every other level list; for bottom-up, reverse the list of levels at the end.

  3. 3Stop at the first gap

    Push children even when they are null. In a complete tree, once you pop a null, every node after it must be null too.

  4. 4Run a check at every node

    Visit every node of the big tree and ask "is the tree starting here the same as the small one?" with the same-tree check. O(m · n) worst case, which is fine for interview sizes.

Mistakes to avoid

  • Reading q.size() inside the for condition: it changes as you push children. Save it first.
  • Zigzag: reversing the order you push children breaks the next level. Keep BFS normal and reverse (or fill from the back) only the level list.
  • In JavaScript, q.shift() is O(n): use a head index or swap in a new array per level.

Mark it done once you can write the template from memory and you have solved the worked examples yourself.