Binary Tree Level Order Traversal
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Return the tree's values level by level, from top to bottom, left to right.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1What order do you want the nodes in? Nearest to the root first.
- Hint 2A queue serves in the order things arrived. How does it help here?
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
Reading an org chart floor by floor. A queue at the lift: the CEO goes first; as each person is processed, their direct reports join the back of the queue. Because everyone on one floor was added before anyone on the next floor, the queue naturally serves floor 1, then floor 2, then floor 3. To separate floors, count how many people are in the queue at the start of each round.
- The obvious way
Compute the depth of every node recursively and bucket by depth: works, but BFS is the natural tool.
- The key insight
Put the root in a queue. Repeat: note how many nodes are in the queue right now (that is exactly one level), take that many from the front, record their values, and append their children to the back. Continue until the queue is empty.
- The algorithm
- Queue starts with the root (if any).
- Count how many are in the queue now: that is this level's size.
- Take that many from the front: record values, add children to the back.
- Save the level; repeat until the queue is empty.
Watch it run
Exampletree = [3, 9, 20, null, null, 15, 7]
Queue = [3]. One person is waiting: that is level 1. Serve 3; its children 9 and 20 join the queue.
levels: [[3]] queue: 9, 20
Where people slip
- Fix the level size BEFORE the inner loop; the queue grows while you serve.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
from collections import deque
def level_order(root):
levels = []
queue = deque([root] if root else [])
while queue:
level = []
for _ in range(len(queue)): # exactly one level
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(level)
return levelsNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.