Loading...
Loading...
Tier II · Intermediate
Layer-by-layer traversal of a binary tree for depth and level order.
Breadth-first search explores a tree level by level using a queue. Nodes come out in order of depth, so every node at depth is dequeued before any node at depth .
| Variant | What each pass does | Typical use |
|---|---|---|
| Early exit | Stop at the first match | Minimum depth, shallowest leaf |
| Level inspection | Check relationships within a depth | Cousins, level averages |
| Level collection | Emit each depth as its own list | Level-order and zigzag views |
The loop is the same every time. Read the queue size, pop that many nodes, and push their children. Everything popped in one round is one level, so you can track depth, compare nodes at a depth, or collect each row. A binary tree has one path to every node, so no visited set is needed until part II.
| Approach | Time | Extra space |
|---|---|---|
| DFS over the whole tree | , tree height | |
| BFS over every level | , widest level | |
| BFS, stop at the first match | Nodes above the match |
Reach for BFS over DFS whenever depth is the question. The shallowest match is the first one dequeued, so you can return right away instead of walking the rest of the tree.
The problems below start with returning at the first leaf dequeued, move to testing whether two nodes are cousins, and end with collecting the tree level by level.
Recommended first: Stacks & Queues.
You've cleared 0 of 8 problems in these. You can dive in anyway.