account_treeBFS / DFS

BFS / DFS: when to spot it, explain it, and practice it

BFS and DFS are less about memorizing traversal syntax and more about knowing whether you are exploring exhaustively, detecting structure, or searching for the shortest layered answer.

Pattern coverage

80+

Best first move

Decide whether the problem needs breadth, depth, or both.

Common failure point

Marking visited too late and enqueuing duplicates.

When this pattern should come to mind

The input is a tree, graph, matrix, or implicit graph of states.
You must visit connected components or reachable states.
The shortest number of steps suggests BFS; complete exploration suggests DFS.

Checklist before you code

Decide whether the problem needs breadth, depth, or both.
Mark visited at the correct moment to avoid repeated work.
For DFS, define the stopping condition before recursing.
For BFS, decide what exactly a level means.

The solving flow that works well in interviews

1

Identify the graph model and how neighbors are generated.

2

Choose BFS for shortest unweighted distance or DFS for structure exploration.

3

Maintain visited consistently so the same state is not processed twice.

4

Track the extra state that the answer depends on, such as level or path sum.

5

Handle disconnected components if the traversal can start from multiple places.

Common variants

Grid traversal

Great for flood fill, island counting, and boundary propagation.

Tree traversal

Useful when parent-child structure and path information matter.

State-space search

Useful when each node is a state, such as word ladder or lock rotation.

Template preview

PythonPublic preview
from collections import deque

def bfs(start):
    queue = deque([start])
    visited = {start}
    while queue:
        node = queue.popleft()
        for nxt in graph[node]:
            if nxt not in visited:
                visited.add(nxt)
                queue.append(nxt)

def dfs(node):
    visited.add(node)
    for nxt in graph[node]:
        if nxt not in visited:
            dfs(nxt)

A more useful problem ladder for practice

This is not a random list. It is ordered to help candidates build recognition first, add key variants next, and then increase pressure with harder cases.

High-frequency mistakes

warning

Marking visited too late and enqueuing duplicates.

warning

Using recursive DFS where depth can overflow the stack.

warning

Mixing path-specific state with global visited state incorrectly.

warning

Forgetting to scan all components when the graph is disconnected.

Recommended practice path

1

Start with grid DFS and island problems.

2

Then solve tree traversal questions and simple graph cloning.

3

After that, move to topological sort and cycle detection.

4

Finish with harder state-space BFS questions such as word ladder.

BFS / DFS Pattern Guide | LeetCode Interview Prep - Interview AiBox