Tree & GraphIntermediate
BFS (Level-Order)
Explore all nodes at the current depth before moving to the next level, using a queue.
Problem: Binary Tree Level Order Traversal
Traverse a binary tree level by level using BFS with a queue.
1
2
3
4
5
6
DefaultIn QueueProcessingVisited
Initialize: enqueue root node
Start BFS by adding the root node (1) to the queue. Queue = [1], Visited = [].
Queue
1
Current Level
0
Output (Level Order)
[]
Visited Order
none yet
Step 1/8
Speed:
When to Use
- Level-order traversal
- Shortest path in unweighted graph
- Find nearest/minimum distance
- Layer-by-layer processing
Key Indicators
- Level by level
- Shortest path (unweighted)
- Nearest neighbor
- Minimum steps/moves
Complexity
Time
O(V + E)
Space
O(V)
Common Problems
Binary Tree Level Order TraversalRotting OrangesWord Ladder01 MatrixShortest Path in Binary Matrix
Code
queue = [root]
while queue:
level_size = len(queue)
for _ in range(level_size):
node = queue.pop(0)
process(node)
for neighbor in node.neighbors:
if not visited:
queue.append(neighbor)Want all 29 patterns with detailed visual walkthroughs?
The complete book includes 84 practice problems, full decision tree, and illustrated step-by-step solutions.
Book Coming Soon ($4.99)