Binary Tree Level Order Traversal (LeetCode 102): Solution and Explanation

Medium
Tree
Breadth First Search
Binary Tree

Given the root of a binary tree, return its node values grouped by depth: the root's value first, then all values on the second level from left to right, then the third level, and so on. The output is a list of lists, one inner list per level.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Depth-first traversals like preorder or inorder dive down one branch before touching the next, so values from different depths come out interleaved. You could still fix that by passing the depth into a recursive call and appending each value to res[depth], but the problem is really asking for breadth-first order, so a queue is the natural tool.

A queue processes nodes in the order they were discovered. Start with the root; when you pop a node, push its children onto the back. Because all children of level d are pushed before any node of level d plus one is popped, the queue naturally holds the tree one level at a time. The only extra question is how to tell where one level ends and the next begins.

The answer is to take a snapshot of the queue's length at the start of each round. Exactly that many nodes belong to the current level, so you pop that many, collect their values into one list, and let their children pile up behind them for the next round. The reference code also pushes None children and simply skips them when popped, which keeps the loop body short at the cost of a few extra queue entries.

Approach: Breadth-first search with level-size snapshots

  1. Create an empty result list res and a deque q containing the root.
  2. While the queue is not empty, record qLen = len(q), the number of entries in the current level.
  3. Pop exactly qLen entries. For each one that is not None, append its value to level and push its left and right children, even if they are None.
  4. After the inner loop, append level to res only if it is non-empty, which filters out rounds made up entirely of None placeholders.
  5. Return res once the queue is drained. An empty tree starts with [None], produces an empty level, and returns [].

Step-by-step example

root = [3,9,20,null,null,15,7]
  1. The queue starts as [3]. Round one pops 3, records [3], and pushes 9 and 20.
  2. Round two has qLen 2. Popping 9 pushes two None children, and popping 20 pushes 15 and 7. The level is [9,20].
  3. Round three has qLen 4: None, None, 15 and 7. The two None entries are skipped, while 15 and 7 are recorded and each pushes two None children. The level is [15,7].
  4. Round four pops four None entries, so level stays empty and is not added.
  5. The queue is empty, and the result is [[3],[9,20],[15,7]].

Code: Python, Java, C++

1class Solution:
2    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
3        res = []
4        q = collections.deque()
5        q.append(root)
6        
7        while q:
8            qLen = len(q)
9            level = []
10            for i in range(qLen):
11                node = q.popleft()
12                if node:
13                    level.append(node.val)
14                    q.append(node.left)
15                    q.append(node.right)
16            if level:
17                res.append(level)
18        return res

Time and space complexity

Time

O(n)

Every real node is pushed and popped once, and each one adds at most two None placeholders, so the total number of queue operations is still linear in n.

Space

O(n)

The queue can hold an entire level at once. In a complete binary tree the last level has about n / 2 nodes, and the output itself stores all n values.

Other approaches

DFS with a depth parameter (time O(n), space O(h))

Recurse with (node, depth). When depth equals len(res), append a new empty list, then add the value to res[depth]. Visiting left before right keeps each level ordered left to right, and the stack only grows to the tree height.

BFS that skips null children (time O(n), space O(n))

Only push a child when it exists, which avoids the None entries and the empty-level check. It is the same algorithm with a slightly smaller queue and needs an explicit early return for an empty root.

Common mistakes

  • Reading len(q) inside the inner loop instead of saving it first. The queue grows as children are pushed, so the level boundary gets lost.
  • Using a Python list with pop(0) instead of collections.deque. Popping from the front of a list is O(n), which makes the traversal quadratic.
  • Pushing None children but forgetting to filter them or to skip empty levels, which produces a trailing empty list or a crash on None.val.
  • Returning [[]] for an empty tree. The correct answer is an empty list.

Frequently asked questions

BFS or DFS for level order traversal?

BFS is the natural fit because a queue already processes nodes level by level. DFS also works if you pass the depth and append into res[depth], and it can use less memory on wide, shallow trees.

How do you know where each level ends in BFS?

Capture the queue length at the start of each round. That count is exactly the number of nodes on the current level, so popping that many entries processes one level and leaves the next level in the queue.

What is the space complexity of level order traversal?

O(n). The queue can hold up to roughly half of the nodes when the bottom level of a complete tree is reached, and the output list stores every value.