Skip to the solution
MediumDSA13 min read

How do you do a level-order (BFS) traversal of a tree?

643 views

The problem

Question presented to candidate: "Given the root of a binary tree, write a Python function that returns its values level by level โ€” the root's level first, and left to right inside each level โ€” as a list of lists. For example, the tree [3, 9, 20, null, null, 15, 7] should give [[3], [9, 20], [15, 7]]."

What a strong answer should cover:

  • Level order is breadth-first search: a FIFO queue, children added left then right.
  • How to group by level: snapshot the queue size at the start of each round (or keep each level in its own list).
  • O(n) time and O(w) space, where w is the widest level โ€” about n/2 for a perfect tree.
  • Python details: collections.deque.popleft() is O(1) while list.pop(0) is O(n); range(len(queue)) is evaluated once, so it works as the size snapshot.
  • The DFS alternative (pre-order with a depth index) and when BFS is preferable (stop early, very deep trees).
  • The usual variants: zigzag, bottom-up, level averages, right-side view.

Code / implementation expected: Yes โ€” level_order(root) returning a list of lists, using collections.deque, in Python 3.

  • trees
  • bfs

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonLevel order with a queue (5 trees)
PythonZigzag, bottom-up, averages, and the DFS cross-check

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 76 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you count unique paths in a grid?

Continue