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 from the root using a queue. Nodes come out in order of depth, so the first time it reaches a node is along the shortest path from the root in edge count.
The loop is the same every time: read the current queue size, pop exactly that many nodes, push their children. Everything popped in one pass is one level, which is what lets you count depth, examine a level as a group, or emit it as a row. A binary tree has one path to every node, so nothing here needs a visited mark; that changes in part II.
Reach for BFS over DFS whenever depth is the answer. The shallowest node satisfying a condition is the first one dequeued, so you can stop the moment you see it instead of walking the whole tree.
The problems below start with the first leaf dequeued being the answer, move to a level examined rather than emitted, and end with the frontier itself as the output.
Recommended first: Stacks & Queues.
You've cleared 0 of 8 problems in these. You can dive in anyway.