Sale: Get 60% Off on all Pro Plans. Buy Now

Binary Tree Level Order Traversal

Medium BFS

Problem

Given the root of a binary tree, return the level order traversal of its nodes' values as a list of lists, where each inner list contains the values of nodes at the same depth from left to right.

  • The number of nodes in the tree is in the range [0, 10⁴]
  • −1000 ≤ Node.val ≤ 1000

Example

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

Starting at the root (3), the algorithm visits nodes level by level. The first level contains only 3. The second level contains 9 and 20, visited from left to right. The third level contains 15 and 7. The BFS queue initially holds the root. At each iteration, nodes currently in the queue represent one level. The algorithm dequeues each node, records its value, and enqueues its children for the next level. This process repeats until all levels are processed.

Approach

Straightforward Solution

A naive approach might attempt a depth-first traversal and then group nodes by depth afterward, which requires extra bookkeeping and is less intuitive for level order traversal.

Core Observation

Level order traversal is a classic breadth-first search (BFS) problem on trees, where nodes are visited level by level. Each level corresponds to nodes reachable in the same number of edges from the root.

Path to Optimal

Preview

The key recognition signals are 'level order' and 'nodes at the same depth', which indicate BFS traversal using a queue. BFS naturally processes nodes in layers, making it ideal for collecting nodes level by level…

Full step-by-step walkthrough on Pro

Optimal Approach

Preview

Use a queue initialized with the root node. While the queue is not empty, process all nodes currently in the queue (which represent one level), record their values, and enqueue their children…

Full step-by-step walkthrough on Pro

Want the full reasoning chain?

Unlock the complete walkthrough, line-by-line analysis, and recall drill.

Unlock Pro

Time

O(n)

Each node is enqueued and dequeued exactly once, resulting in linear time proportional to the number of nodes.

Space

O(n)

The queue can hold up to the maximum number of nodes at any level, which in the worst case is O(n/2) = O(n). The output list also stores all node values.

Pattern Spotlight

BFS (Level Order Traversal on Tree)

When asked to process nodes level by level in a tree, use a queue to explore nodes breadth-first, processing all nodes at the current depth before moving to the next, ensuring natural grouping by levels.

Solution

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

Step-by-Step Solution

1

Initialize Result Container Before BFS Begins

5res = []

Objective

To create the result container that will accumulate one list of values per tree level.

Key Insight

BFS is not just about traversal order; it is also about grouping output by layer. Initializing the result container before any queue work begins makes it clear that each completed level will later be appended into this outer structure.

Interview Quick-Check

Core Logic

Create the outer result list before traversal so each finished level can be appended in order.

State & Boundaries

The result container exists even when the tree is empty, which is why the empty-tree case returns it directly.

2

Handle Empty Tree Edge Case

To immediately return an empty list if the input tree is empty, avoiding unnecessary processing.

3

Initialize BFS Queue with Root Node

To set up the queue data structure with the root node as the starting point for BFS traversal.

4

Process Each Level by Dequeuing Current Nodes and Enqueuing Children

To iterate over the tree level by level, collecting node values and preparing the next level's nodes.

5

Return the Complete List of Levels After BFS Completion

To output the collected list of node values grouped by level after the BFS traversal finishes.

4 more steps with full analysis available on Pro.

Line Analysis

This solution has 1 Critical line interviewers watch for.

Line 13 Critical
for i in range(len(q)):

Iterate exactly over the number of nodes currently in the queue (current level size).

Capturing the queue length before iteration is critical to isolate nodes of the current level, preventing interference from newly enqueued child nodes and preserving level boundaries.

Full line-by-line criticality + rationale for all 15 lines available on Pro.

Test Your Understanding

Why does BFS guarantee that nodes are processed level by level in a binary tree?

See the answer with Pro.

Related Problems

BFS pattern

Don't just read it. Drill it.

Reconstruct Binary Tree Level Order Traversal from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.

Unlock the Binary Tree Level Order Traversal drill

or drill a free problem