Ankit KanojiyaIntermediate

Evergreen guide by Ankit Kanojiya · Intermediate · DSA

Trees and Graphs: BFS and DFS Traversal

The two foundational graph traversals explained with trees, grids, and general graphs. Covers when to prefer breadth-first over depth-first and how to avoid revisiting nodes.

Most problems about trees, grids, and networks reduce to visiting nodes in a disciplined order. Two traversals cover nearly all of them: breadth-first search, which explores level by level using a queue, and depth-first search, which dives as deep as possible using a stack or recursion. Both run in O(V + E) time, visiting every vertex and edge once.

Trees as a Starting Point

A tree is a graph with no cycles and one path between any two nodes, so traversal never needs to guard against revisiting. Depth-first traversal of a binary tree has three orders defined by when the node is processed relative to its children.

def inorder(node, out):
    if node is None:
        return
    inorder(node.left, out)
    out.append(node.val)       # left, node, right
    inorder(node.right, out)

Inorder on a binary search tree yields sorted values. Preorder processes the node before its children and is useful for copying a tree. Postorder processes children first and suits deletion and computing subtree aggregates. Each is O(n) time and O(h) space for the recursion stack, where h is the height.

Breadth-First Search

BFS visits all neighbors at the current distance before moving outward. It uses a queue, adding neighbors to the back and processing from the front.

from collections import deque

def bfs_levels(root):
    if root is None:
        return []
    result = []
    q = deque([root])
    while q:
        level = []
        for _ in range(len(q)):      # fixed count = current level
            node = q.popleft()
            level.append(node.val)
            if node.left:  q.append(node.left)
            if node.right: q.append(node.right)
        result.append(level)
    return result

Processing exactly the queue length at each step cleanly separates levels. BFS is the natural choice when the answer depends on distance from a source, because the first time it reaches a node is along a shortest path in edge count.

Depth-First Search on General Graphs

General graphs contain cycles, so a visited set is required or the traversal loops forever. The graph is usually stored as an adjacency list mapping each node to its neighbors.

def dfs(graph, start):
    visited = set()
    order = []
    def visit(node):
        visited.add(node)
        order.append(node)
        for nxt in graph[node]:
            if nxt not in visited:
                visit(nxt)
    visit(start)
    return order

The iterative form replaces recursion with an explicit stack, which avoids stack overflow on deep graphs.

def dfs_iterative(graph, start):
    visited = set()
    stack = [start]
    order = []
    while stack:
        node = stack.pop()
        if node in visited:
            continue
        visited.add(node)
        order.append(node)
        for nxt in graph[node]:
            if nxt not in visited:
                stack.append(nxt)
    return order

Shortest Path on Unweighted Graphs

BFS finds the fewest edges from a source to every reachable node. Marking distance as each node is first dequeued guarantees correctness because BFS reaches nodes in nondecreasing distance order.

def shortest_hops(graph, start):
    dist = {start: 0}
    q = deque([start])
    while q:
        node = q.popleft()
        for nxt in graph[node]:
            if nxt not in dist:
                dist[nxt] = dist[node] + 1
                q.append(nxt)
    return dist

For weighted edges this does not hold; Dijkstra or a similar algorithm is needed instead.

Grids as Graphs

A two-dimensional grid is a graph where each cell connects to its orthogonal neighbors. Counting islands, a connected-components problem, uses either traversal from each unvisited land cell.

def count_islands(grid):
    rows, cols = len(grid), len(grid[0])
    seen = set()
    def flood(r, c):
        stack = [(r, c)]
        while stack:
            x, y = stack.pop()
            if (x, y) in seen:
                continue
            seen.add((x, y))
            for dx, dy in ((1,0),(-1,0),(0,1),(0,-1)):
                nx, ny = x + dx, y + dy
                if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 1 and (nx, ny) not in seen:
                    stack.append((nx, ny))
    count = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 1 and (r, c) not in seen:
                flood(r, c)
                count += 1
    return count

Choosing Between Them

  • Shortest path in edges, or a level-by-level answer: BFS.
  • Exploring all paths, detecting cycles, topological ordering, or subtree computations: DFS.
  • Very deep graphs where recursion could overflow: iterative DFS or BFS.
  • Memory matters: DFS uses O(h) stack space on a tree, while BFS can hold a whole level, which is wide near the bottom.

Common Mistakes

  • Forgetting the visited set on a cyclic graph, causing infinite loops.
  • Marking a node visited when dequeuing rather than when enqueuing in BFS, which can add duplicates to the queue.
  • Confusing distance in edges with weighted distance.

With these two traversals and a visited set, the majority of tree and graph problems become variations on a familiar template.