Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get the root of a binary tree. Return a list of lists: the first list holds the root's value, the second holds every value one level down (left to right), and so on. An empty tree gives an empty list.
The tree has up to 2,000 nodes.
Example: [3, 9, 20, null, null, 15, 7] → [[3], [9, 20], [15, 7]].
3 level 0: [3]
/ \
9 20 level 1: [9, 20]
/ \
15 7 level 2: [15, 7]Start with brute force
One way: first find the tree's height h (see Maximum Depth of Binary Tree). Then, for each depth d from 0 to h − 1, walk the whole tree from the root and collect the nodes at depth d, visiting left before right.
It's correct, and left-before-right gives the right order inside each level. But each of the h passes walks down from the root again. For a chain of 2,000 nodes, that's about 2,000 × 2,000 / 2 = 2 × 10⁶ steps for something that should take 2,000.
Building the intuition
Imagine people standing in a queue at a ticket counter. When someone reaches the counter, they tell their two children to join the back of the queue. Who gets served when?
- The root is served first and sends
9and20to the back. 9is served (no children).20is served and sends15and7to the back.15and7are served.
Everyone on level 1 joined before anyone on level 2, because level-2 nodes are only added when level-1 nodes are served. So a queue (first in, first out) visits a tree level by level. This is breadth-first search (BFS): spread across the width before going deeper. Recursion, which uses a stack, does the opposite: it goes deep first (DFS).
One problem left: the queue is just one long line. How do you know where level 1 ends and level 2 begins?
Look at the moment just before you start serving level 1. The queue holds exactly level 1 and nothing else, because the root has been served and nobody from level 1 has been served yet. So read the queue's size right then. Serve exactly that many people. They're the whole level, and everything they add behind them is the next level.
The optimal approach
- If
rootisnull, return[]. - Put
rootin a queue. - While the queue isn't empty:
size = len(queue). This is the number of nodes on the current level.- Pop
sizenodes. For each one, add its value toleveland push its non-null children. - Append
levelto the result.
- Return the result.
The subtle detail: read the size once, before the inner loop. If you write for i in range(len(queue)) in a language that re-checks the length every time, or loop while queue inside, the children you push join the current level and the rows blur together.
In JavaScript, array.shift() is O(n), which would make the whole thing O(n²) in the worst case. The JavaScript solution keeps a head index instead, so popping is O(1).
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
from collections import deque
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
result = []
if root is None:
return result
queue = deque([root])
while queue:
# Everything in the queue right now is exactly one level.
# Freeze its size before we start adding the next level behind it.
size = len(queue)
level = []
for _ in range(size):
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 resultclass Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> result;
if (root == nullptr) return result;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
// Everything in the queue right now is exactly one level.
// Freeze its size before we start adding the next level behind it.
int size = q.size();
vector<int> level;
for (int i = 0; i < size; i++) {
TreeNode* node = q.front();
q.pop();
level.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
result.push_back(level);
}
return result;
}
};class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
// Everything in the queue right now is exactly one level.
// Freeze its size before we start adding the next level behind it.
int size = queue.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
result.add(level);
}
return result;
}
}/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function (root) {
const result = [];
if (root === null) return result;
// An array plus a head index is a queue with O(1) pops (shift() is O(n)).
const queue = [root];
let head = 0;
while (head < queue.length) {
// Everything between head and the end is exactly one level.
// Freeze its size before we start adding the next level behind it.
const size = queue.length - head;
const level = [];
for (let i = 0; i < size; i++) {
const node = queue[head++];
level.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
result.push(level);
}
return result;
};Dry run
Tree [3, 9, 20, null, null, 15, 7].
| Round | Queue at start | size | Popped (pushes) | level |
|---|---|---|---|---|
| 1 | [3] | 1 | 3 (push 9, 20) | [3] |
| 2 | [9, 20] | 2 | 9 (none), 20 (push 15, 7) | [9, 20] |
| 3 | [15, 7] | 2 | 15 (none), 7 (none) | [15, 7] |
| end | [] | — | — | — |
Result: [[3], [9, 20], [15, 7]].
Complexity
- Time: O(n). Every node is pushed once and popped once.
- Space: O(n). The queue holds at most one full level. The bottom level of a complete tree has about
n/2nodes, so that's O(n). The output itself is also O(n).
Edge cases and traps
- Empty tree. Return
[], not[[]]. Check fornullbefore seeding the queue. - Pushing
nullchildren. Only push real children, or you'll pop anulland crash on.val. - Size read inside the loop. Freeze it before popping. Otherwise the next level leaks into this one.
shift()in JavaScript. It moves every element. Use a head index, or swap in a fresh array each level.- Using a stack. A stack gives you DFS order. Levels come out scrambled.
Say it in the interview
"This is BFS. A queue hands nodes back in the order I found them, so the tree comes out level by level. To separate the levels, at the start of each round I record how many nodes are in the queue. That's exactly the current level, so I pop that many, record their values, and push their children for the next round. Every node goes in and out once, so it's O(n) time, and the queue holds at most one level, which is O(n) in the worst case."
Follow-ups interviewers ask
- "Can you do it with DFS?" Yes. Pass the depth down:
dfs(node, depth). Ifdepth == len(result), start a new row. Append the value toresult[depth], then recurse left before right. Each row still comes out left to right. - "Return the levels bottom-up." Do the same BFS, then reverse the list of levels at the end. It's still O(n).
- "Zigzag order: left-to-right, then right-to-left, alternating." Do the same BFS and reverse every other
levelbefore appending it (or fill it from the back).
Practise the same idea
This is Day 54 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free