Difficulty: Medium | Asked at: Amazon, Microsoft, LinkedIn
Given a binary tree, return its values level by level (BFS).
3
/ \
9 20
/ \
15 7
Output: [[3], [9, 20], [15, 7]]
💡 Hint: BFS naturally processes a tree level by level using a queue. The trick is tracking how many nodes belong to the CURRENT level before you start adding next-level nodes to the same queue.
Solution:
python
from collections import deque
def level_order(root):
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
current_level = []
for _ in range(level_size):
node = queue.popleft()
current_level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(current_level)
return result
Complexity: O(n) time and space - every node is visited and queued exactly once.
Common mistake: Forgetting to snapshot
level_size = len(queue) BEFORE the inner loop starts. If you check len(queue) inside the loop, it changes as you enqueue children, and your levels get mixed together.BFS with a queue vs. DFS with recursion - do you know when to reach for each? That's often the actual follow-up question here 👇