MohitDecodes
Back to blogsDSA

Mastering Trees and Graphs for Coding Interviews

November 4, 2026 · 7 min read

Trees and graphs scare candidates mostly because the problem statements rarely say the word "graph". They talk about islands in a matrix, course prerequisites, word ladders, or network delays — underneath, they all reduce to the same handful of traversals.

BFS vs DFS: how to choose in 10 seconds

  • Use **BFS (Queue)** when the problem asks for minimum steps, shortest path in an unweighted graph, or level-order traversal.
  • Use **DFS (Recursion / Stack)** when you need to explore connected components, detect cycles, or check all paths.
  • Use **Topological Sort (Kahn's Algorithm)** when items depend on prerequisites (build order, course schedule).
// BFS template for shortest path in unweighted graph / grid
const queue = [[start, 0]];
const visited = new Set([start]);

while (queue.length > 0) {
  const [node, dist] = queue.shift();
  if (node === target) return dist;
  for (const next of graph[node]) {
    if (!visited.has(next)) {
      visited.add(next);
      queue.push([next, dist + 1]);
    }
  }
}

One golden habit: mark nodes as `visited` **when pushing onto the queue**, not when popping — otherwise the same node gets pushed multiple times and causes TLE on dense graphs.