Skip to content

Binary Tree Level Order Traversal

MediumLeetCode #102Time O(n)Space O(n)

You get the root of a binary tree. Return a list of lists: the first holds the root, the second holds its children left to right, the third holds the grandchildren, and so on. An empty tree gives an empty list.

[3, 9, 20, null, null, 15, 7] -> [[3], [9, 20], [15, 7]]

Recursion (DFS) dives to the bottom before it visits the neighbours, which is the wrong order for “row by row”. Breadth-first search visits nodes in exactly the order you want, and a queue gives you that: take a node from the front, push its children onto the back.

The only extra problem is knowing where one level ends. The trick: at the start of each pass, the queue holds exactly the nodes of the current level. Read len(queue) once, then process that many nodes. Everything they push is the next level, and waits for the next pass.

Show solutionHide solution
from collections import deque
def level_order(root: TreeNode | None) -> list[list[int]]:
result = []
queue = deque([root] if root else [])
while queue:
level = []
for _ in range(len(queue)): # freeze the size: exactly one level
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
  • Time: O(n) — each node is enqueued and dequeued once.
  • Space: O(n) — the queue holds one whole level at a time, up to about n/2 nodes for the widest level, and the output itself stores all n values.
  • Freeze the level size before the inner loop. If you re-read len(queue) while pushing children, levels bleed into each other. In Python range(len(queue)) does this for you.
  • Guard the empty tree. Don’t put None in the queue; start with an empty queue when the root is missing, or you will read None.val.
  • Use a real queue. In Python use deque.popleft(); list.pop(0) is O(n) per call. JavaScript arrays have the same problem with shift(), so the TypeScript solution builds each level as its own array instead: same BFS, no dequeue needed.

Binary Tree Right Side View (LeetCode 199)

Section titled “Binary Tree Right Side View (LeetCode 199)”

What you would see looking from the right. The trick: same level-by-level BFS, but keep only the last node of each level.

Binary Tree Zigzag Level Order Traversal (LeetCode 103)

Section titled “Binary Tree Zigzag Level Order Traversal (LeetCode 103)”

Alternate direction each level. The trick: run the normal BFS, then reverse every other level’s list (or append to the front of it) before adding it to the result.

Binary Tree Level Order Traversal II (LeetCode 107)

Section titled “Binary Tree Level Order Traversal II (LeetCode 107)”

Levels from the bottom up. The trick: run the same BFS and reverse the list of levels at the end. O(n).