Problem 102 · LeetCode 102(opens in a new tab)
Binary Tree Level Order Traversal
MediumBreadth-first search
You get root, the top node of a binary tree. Read the tree one row at a time: first the root, then its children, then their children, and so on.
Return a list of rows. Each row is a list of the values at that depth, written left to right. An empty tree gives an empty list.
Example 1
Input: root = [8, 4, 11, null, 6, 10, 15] Output: [[8], [4, 11], [6, 10, 15]] Why: 6 is the right child of 4; 10 and 15 hang under 11
2 more examples and the constraints
Example 2
Input: root = [5, null, 7, null, 9] Output: [[5], [7], [9]] Why: each node has only a right child, so each row has one value
Example 3
Input: root = [] Output: [] Why: no nodes, so no rows
Constraints
- 0 ≤ number of nodes ≤ 2,000
- −1,000 ≤ each value ≤ 1,000
- Trees are written in level order, with null for a missing child
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- One search per levelO(n·h)
- DFS with a depth indexO(n)
- BFS, one level at a timeO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a chain of 2,000 nodes | Verdict |
|---|---|---|---|
| One search per level | O(n·h) | Mention it, then move on | |
| DFS with a depth index | O(n) | Passes; deep recursion | |
| BFS, one level at a time | O(n) | Best; the expected answer |
n = number of nodes, h = height of the tree.
Edge cases to test
- Empty tree. A null root returns [], not [[]]. Check before putting the root in the queue.
- Single node. [42] gives [[42]]: one row with one value.
- A chain. [5, null, 7, null, 9] has one value per row and is as deep as it is long.
- Gaps inside a level. [1, 2, 3, null, 4, 5] gives [[1], [2, 3], [4, 5]]: missing children leave no holes in a row.
Common mistakes
- Reading the queue size inside the loop instead of once per level, so children leak into the current row.
- Pushing a null child into the queue and then reading its value.
- Using
shift()on a JavaScript array as the queue: each call is O(n), which makes the whole walk O(n²).
How to talk through it
- 1Clarify. Should rows go left to right? What should an empty tree return?
- 2Name the pattern. Grouping by depth is breadth-first search: a queue gives nodes back level by level.
- 3Explain the level boundary. At the start of each round the queue holds exactly one level, so its size tells you how many nodes to take.
- 4Mention the DFS option. A recursive walk that passes the depth also works in O(n); say it uses the call stack instead of a queue.
- 5Test out loud. Run the empty tree, a single node and a chain before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?