mediumTreeBFSTrees

Binary Tree Level Order Traversal

mediumTime: O(n)Space: O(n)

Signals to notice

visit nodes level by levelBFS on a treegroup nodes by depth

Brute force first

DFS with depth tracking, then sort by depth. Adds unnecessary sorting when BFS naturally processes by level. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

BFS with a queue: process all nodes at the current depth, then move to the next level. Track the level size to know when one level ends and the next begins. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

At the start of each level, the queue contains exactly the nodes at that depth. Processing them all before adding their children keeps levels separate. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Not tracking the level boundary — without knowing how many nodes are in the current level, you can't separate levels in the output. The fix is usually to return to the meaning of each move, not just the steps themselves.

Trees Pattern