Binary Tree Level Order Traversal
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given the root of a binary tree, return its values level by level: one array per level, from the root down, and left to right within each level.
Understand the problem
- A tree's levels are its "floors": the root is level 0, its children are level 1, their children are level 2, and so on.
- You return an array of arrays. The first inner array holds the root's value, the second holds the values on level 1 (left to right), and so on.
Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: [[3], [9, 20], [15, 7]]
3 ← level 0
/ \
9 20 ← level 1
/ \
15 7 ← level 2Example 2
Input: root = [1]
Output: [[1]]One node, one level.
Example 3
Input: root = []
Output: []An empty tree has no levels.
How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child.
Constraints
0 <= number of nodes <= 2000
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Keep a list of the nodes on the current level; record their values, then build the next level from their children, and repeat until there are no nodes left.
The key insight
Most tree code uses recursion, which goes deep first: all the way down the left branch before even looking at the right. This problem wants the opposite: go wide, one full level at a time. That's breadth-first search (BFS).
The trick is to notice that the children of one level, in order, are the next level:
level 0: [3]
children of 3 → 9, 20 → level 1: [9, 20]
children of 9 → none, of 20 → 15, 7 → level 2: [15, 7]
children of 15 and 7 → none → stopBecause we go through each level left to right and add the left child before the right one, the next level comes out in the right order automatically.
Step by step
root = [3, 9, 20, null, null, 15, 7]:
| Current level | Values recorded | Next level (their children) | Result so far |
|---|---|---|---|
[3] | [3] | [9, 20] | [[3]] |
[9, 20] | [9, 20] | [15, 7] | [[3], [9, 20]] |
[15, 7] | [15, 7] | [] | [[3], [9, 20], [15, 7]] |
[] | stop |
The code
The reference solution is below, with comments on every important line. JavaScript and TypeScript build a new array for each level; Python uses one deque (a fast queue) and reads its size before each level. Both do the same thing.
How fast is it?
- Time: O(n). Every node is added and recorded once.
- Memory: O(w), where
wis the widest level. In a full tree, the bottom level holds about half the nodes.
Common mistakes
- Mixing levels together. With a single queue, if you just keep popping, you lose track of where one level ends. Read the size (or use a separate array per level) first.
- Using
array.shift()in JavaScript as a queue on big inputs. It's O(n) per call, because it moves every remaining element. Building a new array per level avoids it. - Forgetting the empty tree.
root = nullmust return[], not[[]].
Going deeper
This "one level at a time" BFS is the base for many variants: zigzag order (reverse every other level), the right side view (last value of each level), and the average of each level. The same BFS idea, on graphs instead of trees, finds shortest paths in unweighted graphs.
Reference solution
/**
* @param {TreeNode | null} root
* @return {number[][]}
*/
export default function levelOrder(root) {
const result = []
// The nodes on the current level, left to right. Level 0 is just the root.
let level = root ? [root] : []
while (level.length > 0) {
// Record this level's values as one array.
result.push(level.map((node) => node.val))
// The children of this level, in order, ARE the next level.
const next = []
for (const node of level) {
if (node.left) next.push(node.left)
if (node.right) next.push(node.right)
}
level = next
}
return result
}export default function levelOrder(root: TreeNode | null): number[][] {
const result: number[][] = []
// The nodes on the current level, left to right. Level 0 is just the root.
let level: TreeNode[] = root ? [root] : []
while (level.length > 0) {
// Record this level's values as one array.
result.push(level.map((node) => node.val))
// The children of this level, in order, ARE the next level.
const next: TreeNode[] = []
for (const node of level) {
if (node.left) next.push(node.left)
if (node.right) next.push(node.right)
}
level = next
}
return result
}from collections import deque
def level_order(root: TreeNode | None) -> list[list[int]]:
result = []
queue = deque([root] if root else []) # a queue: add at the back, take from the front
while queue:
values = []
# Everything in the queue right now is one level: take exactly that many nodes.
for _ in range(len(queue)):
node = queue.popleft()
values.append(node.val)
# Their children go to the back of the queue: they're the next level.
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(values)
return result