BFS (Level Order Traversal)
The foundation for Graphs and Trees. Use for shortest path in unweighted graphs or level-by-level processing.
Recognition
- Shortest path in an unweighted graph.
- Level-order traversal of trees or grids.
When not to use it
Do not force this pattern when the input is unordered and hashing is enough.
Avoid coding the template before naming the invariant you need to preserve.
Logic template
Python
from collections import deque
def bfs(root):
if not root: return []
queue = deque([root])
res = []
while queue:
level_size = len(queue)
current_level = []
for _ in range(level_size):
node = queue.popleft()
current_level.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
res.append(current_level)
return resJavaScript
function bfs(root) {
if (!root) return [];
const queue = [root];
const res = [];
while (queue.length > 0) {
const levelSize = queue.length;
const currentLevel = [];
for (let i = 0; i < levelSize; i++) {
const node = queue.shift();
currentLevel.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
res.push(currentLevel);
}
return res;
}Typically better than the obvious O(N^2) approach; verify with the template.
- Name what stays true after every move.
- Track the exact condition that lets you discard work safely.
Worked example
Recognition drill
Identify the reusable state and the rule that advances it.
- Restate the goal in one sentence.
- Name the moving parts and what they represent.
- Write the loop invariant before coding.
- Trace one failing case that breaks a naive approach.
Result: You can explain when to reach for the pattern and when to abandon it.
Common pitfalls
- Off-by-one updates on loop bounds.
- Updating state after comparing instead of before.
- Confusing “solved once” with pattern mastery.