Problem Statement

Binary Tree Level Order Traversal

You are given the root of a binary tree. A binary tree is a structure where you start at one node (the root) and each node can point to a left child and a right child. Your job is to return the values level by level: first the root by itself, then everything one step down, then everything two steps down, and so on. Inside each level you read the nodes from left to right. The answer is a list of lists, one inner list per level.

mediumTreeBFSTreesTime: O(n) · Space: O(n)

Signals to notice

visit nodes level by levelBFS on a treegroup nodes by depth

Brute force first

DFS with depth tracking, then sort by depth. Adds unnecessary sorting when BFS naturally processes by level. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

BFS with a queue: process all nodes at the current depth, then move to the next level. Track the level size to know when one level ends and the next begins. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Trace it on root = [3,9,20,null,null,15,7]

init: queue=[3], result=[]
level start: level_size=1, level=[] -> pop 3, level=[3], enqueue 9,20 -> queue=[9,20]; result=[[3]]
level start: level_size=2, level=[] -> pop 9 (no kids), level=[9]; pop 20, enqueue 15,7, level=[9,20] -> queue=[15,7]; result=[[3],[9,20]]
level start: level_size=2, level=[] -> pop 15 (no kids), level=[15]; pop 7 (no kids), level=[15,7] -> queue=[]; result=[[3],[9,20],[15,7]]
queue empty -> return [[3],[9,20],[15,7]]

What must stay true

At the start of each level, the queue contains exactly the nodes at that depth. Processing them all before adding their children keeps levels separate. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Shape of the loop

queue = [root]; result = []
while queue not empty:
    level_size = len(queue); level = []
    repeat level_size times:
        node = queue.popleft(); level.append(node.val)
        enqueue node.left and node.right if present
    result.append(level)
return result

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not tracking the level boundary — without knowing how many nodes are in the current level, you can't separate levels in the output. The fix is usually to return to the meaning of each move, not just the steps themselves.

Trees Pattern