Loading…
Binary Tree Level Order Traversal is a medium coding interview question covering graphs, trees, breadth-first search — the kind asked at FAANG (Facebook/Meta, Apple, Amazon, Netflix, Google) and AI-first companies like Anthropic, OpenAI, and Nvidia.
Given the root of a binary tree, return the values of its nodes level by level: a list of lists where the i-th list contains all values at depth i, left to right.
Try it yourself first
In an interview you'd get about 25 minutes for a medium question. Sketch an approach before peeking — struggling is where the learning happens.
Stuck? Reveal them one at a time — each hint gives away a little more.
Ready to compare notes? The full solution, visualization, and complexity analysis are below.
Breadth-first search with a queue. Snapshot the queue length at the start of each round — exactly that many nodes belong to the current level. Pop them all, collect their values, and push their children for the next round.
| 1 | from collections import deque |
| 2 | |
| 3 | def level_order(root) -> list[list[int]]: |
| 4 | if not root: |
| 5 | return [] |
| 6 | levels = [] |
| 7 | queue = deque([root]) |
| ▶ | while queue: |
| ▶ | size = len(queue) |
| ▶ | level = [] |
| ▶ | for _ in range(size): |
| ▶ | node = queue.popleft() |
| ▶ | level.append(node.val) |
| ▶ | if node.left: queue.append(node.left) |
| 15 | if node.right: queue.append(node.right) |
| 16 | levels.append(level) |
| 17 | return levels |
Level 0: pop 3, collect it, and queue its two children.
Queue [3]. Level size 1 -> level [3]. Push 9, 20.
Key Insights
A full interview loop is more than one round. These are the others, each with what is on the site for it.