Problem 107 · LeetCode 107(opens in a new tab)
Binary Tree Level Order Traversal II
MediumBreadth-first search
You get root, the top node of a binary tree. Group its values by depth, with each group read from left to right.
Return the groups starting from the deepest level and ending with the root on its own. An empty tree gives an empty list.
Example 1
Input: root = [6, 2, 13, null, 5, 9, 17] Output: [[5, 9, 17], [2, 13], [6]] Why: the bottom row is 5, 9, 17; the root comes last
2 more examples and the constraints
Example 2
Input: root = [4, null, 8, 3] Output: [[3], [8], [4]] Why: one node per level, deepest first
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 walk per level, deepest firstO(n·h)
- DFS with a depth index, then reverseO(n)
- BFS by level, then reverseO(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 walk per level | O(n·h) | Mention it, then move on | |
| DFS with a depth index | O(n) | Passes; deep recursion | |
| BFS by level, then reverse | 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 pushing it.
- Single node. [-7] gives [[-7]]: one row, so reversing changes nothing.
- A chain. [4, null, 8, 3] has one value per row and is as deep as it is long.
- Rows stay left to right. Only the order of the rows flips. [1, 2, 3, 4] gives [[4], [2, 3], [1]], not [[4], [3, 2], [1]].
Common mistakes
- Reversing the values of the whole traversal instead of the list of rows, which flips each row too.
- Inserting each new row at the front of an array list: each insert shifts every row, which is O(h²) for a deep tree. Append, then reverse once.
- Reading the queue size inside the loop instead of once per level, so children leak into the current row.
How to talk through it
- 1Clarify. Deepest row first, but each row still left to right? What does an empty tree return?
- 2Spot the twist. This is a plain level-order walk with the rows in the opposite order.
- 3Explain the level boundary. At the start of each round the queue holds one level, so its size tells you how many nodes to take.
- 4Flip at the end. Append rows and reverse once, O(h), rather than inserting at the front every time.
- 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?