Browse curriculum

Binary Tree Level Order Traversal

Return a binary tree's values level by level with BFS: read the queue size to know how many nodes form the current level, then enqueue their children.

Problem Understanding

Binary Tree Level Order Traversal: given the root of a binary tree, return its node values level by level, left to right, as a list of lists.

Example: root = [3, 9, 20, null, null, 15, 7] returns [[3], [9, 20], [15, 7]].

The Intuition: The Queue Holds One Level at a Time

Breadth-first search already visits a tree level by level; the only work is knowing where each level ends.

  1. Start with the root in a queue.
  2. At the top of each pass, the queue contains exactly one level. Read size = len(queue).
  3. Dequeue size nodes, recording their values and enqueuing their children.
  4. Append the recorded list as one row; the queue now holds the next level.

The same loop with one extra step solves Zigzag Level Order (reverse every other row) and Binary Tree Right Side View (keep the last node of each row).

Interactive Walkthrough

The tree numbers each node #n in the order it is dequeued. Beside it are the queue, the level being collected and the finished rows. Try Lopsided to see a level that holds a single node.

Dry Run Table

Input: root = [3, 9, 20, null, null, 15, 7]

Pass Queue at start Size Row Queue after
1 [3] 1 [3] [9, 20]
2 [9, 20] 2 [9, 20] [15, 7]
3 [15, 7] 2 [15, 7] []

Answer: [[3], [9, 20], [15, 7]].

The Solution Template

BFS with the queue size read at the start of each level.

Binary Tree Level Order Traversal Code
1var levelOrder = function(root) {
2 const result = [];
3 if (!root) {
4 return result;
5 }
6 const queue = [root];
7 let head = 0;
8 while (head < queue.length) {
9 const size = queue.length - head;
10 const level = [];
11 for (let i = 0; i < size; i++) {
12 const node = queue[head++];
13 level.push(node.val);
14 if (node.left) {
15 queue.push(node.left);
16 }
17 if (node.right) {
18 queue.push(node.right);
19 }
20 }
21 result.push(level);
22 }
23 return result;
24};

Edge Cases & Common Mistakes

  • Empty tree: return [], not [[]].
  • Using len(queue) inside the loop condition: the queue grows while you iterate; read the size once before the inner loop.
  • Enqueuing null children: skip them, or every level fills up with nulls.
  • Using a list as a queue in Python: list.pop(0) is O(n); use collections.deque.
  • Bottom-up variant (LeetCode 107): run the same loop and reverse the result at the end.

Summary

Put the root in a queue. Each pass, read the queue size, dequeue that many nodes into one row, and enqueue their children for the next pass. Append the rows until the queue is empty. O(n) time and O(w) space, where w is the widest level.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start the queue

    Return [] for an empty tree; otherwise put the root in a queue.

  2. Take one level per pass

    Read the queue size, then dequeue that many nodes, appending each value to a level list and enqueuing its non-null children.

  3. Collect the rows

    Append each level list to the result until the queue is empty.

Frequently asked questions

How does BFS separate a binary tree into levels?

At the start of each pass the queue holds exactly the nodes of one level. Read its size first, dequeue that many nodes into a list, and enqueue their children. Those children are the next level, so each pass produces one row of the answer.


Why read the queue size before the inner loop?

Children are added to the queue while the level is being processed. Reading the size first fixes how many nodes belong to the current level, so the new children wait for the next pass instead of being mixed into this row.


Can level order traversal be done with DFS?

Yes. Pass the depth into a recursive function and append each value to result[depth], creating the row the first time a depth is reached. It gives the same answer, but BFS matches the problem's shape more directly.

Applying for software engineering roles? Free, no sign-up:

AI resume checker — match your resume to the job description