Skip to content

Lesson 21 of 27Decode by category

Decoding Trees and Graphs

Decide between DFS, BFS, topological sort, union-find, and Dijkstra from words like shortest, levels, and dependencies.

16 min read0/5 questions

Tree and graph questions rarely say "use BFS". They say "minimum number of minutes", "in what order can you take the courses", or "how many groups of friends". Each phrase maps to one algorithm almost every time, and recognising that mapping in the first minute is what lets you spend the rest of the interview on the details.

This lesson builds that map: first what kind of structure you have, then which traversal or algorithm the wording asks for. The algorithms themselves are taught in the Algorithms & Patterns course: Trees; Graphs; Union-Find in Depth; Shortest Paths: BFS, 0-1 BFS, Dijkstra, Bellman-Ford; and Cycles, Ordering and Bipartite Graphs.

Step one: tree, graph, or grid?

You seeStructureWhat it changes
"root", "binary tree", TreeNode, "left and right child"TreeNo cycles, one path between nodes. No visited set needed.
"edges", "connections", "prerequisites", "flights", "friends"GraphCycles are possible. You must track visited nodes.
A 2D array of cells, moves "up, down, left, right"Grid (an implicit graph)Each cell is a node, neighbours are the 4 (or 8) adjacent cells.
A list of words where each step changes one letterImplicit graphYou build the edges yourself, often on the fly.

The grid case catches people out. Number of Islands never mentions graphs, but each land cell is a node and each pair of touching land cells is an edge. Once you see that, it is plain connected components.

A note on directed versus undirected: "a depends on b", "a must come before b", "a flight from x to y" are one-way edges. "a and b are friends" or "roads connect" are two-way. Get this right before you build the adjacency list.

Step two: which algorithm?

WordingAlgorithmWhy
"shortest path", "minimum steps", "fewest moves" (no weights)BFSBFS visits nodes in order of distance, so the first time you reach the target is the shortest.
"level by level", "each depth", "right side view"BFSA queue processes one level fully before the next.
"nearest" from several sources at once, "minutes until all"Multi-source BFSPut every source in the queue at time 0.
"count the islands / groups", "can you reach", "explore all"DFS (or BFS)Any full traversal works; DFS is the shortest to write.
A value computed from children: height, diameter, balancedDFS, post-orderYou need the children's answers before the parent's.
"prerequisites", "order of tasks", "dependencies", "is it possible to finish"Topological sortA valid order exists exactly when the directed graph has no cycle.
"are these connected", "redundant edge", "merge accounts", edges arrive over timeUnion-findNear O(1) merge and same-group checks.
"cheapest", "minimum time" with weights on edgesDijkstraBFS is wrong when edges have different costs. Non-negative weights only.

Levels mean BFS

Here is level-order traversal on a small tree. The queue holds exactly one level at a time, which is why "levels" is a BFS word.

BFS processes one level at a time
9315207

result: [[3]]

The queue starts with the root. Level 0 is [3].

1/4
Predict the outputPython

What does this print?

from collections import deque

graph = {"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": ["E"], "E": []}
dist = {"A": 0}
queue = deque(["A"])
while queue:
  node = queue.popleft()
  for nxt in graph[node]:
      if nxt not in dist:
          dist[nxt] = dist[node] + 1
          queue.append(nxt)
print(dist["E"])
Need a nudge? Hints walk you through it.

Weights mean Dijkstra

The moment edges carry different costs, "fewest edges" and "cheapest" stop being the same thing. Look at this graph.

Fewest edges is not cheapest
ABCD10222

currentwaitingdone

We want the cheapest route from A to D.

1/3

The deciding clue is whether the prompt gives a number per edge: travel times, prices, effort. If every edge costs the same (or the prompt only counts steps), BFS is correct and simpler. If weights are only 0 or 1, a deque-based BFS works too, which is a nice thing to mention.

Quick check
'Return the minimum number of moves for a knight to reach a target square.' Every move is one step. Which algorithm?
Need a nudge? A hint rules out a wrong answer.

Dependencies mean topological sort

"Course B requires course A" is a directed edge A → B. "Can you finish all courses?" is "does this graph have a cycle?". "In what order?" is a topological order. Kahn's algorithm takes every node with no remaining prerequisites, removes it, and repeats.

Kahn's algorithm on course prerequisites
Introin 0DSAin 1Webin 1Systemsin 2

currentwaitingdone

Count incoming edges. Only Intro has zero, so it goes in the queue.

1/4

Connected means DFS or union-find

"How many groups?" on a fixed graph is a traversal: start DFS from each unvisited node and count how many times you start. Union-find shines when edges arrive one at a time and you must answer "are these connected yet?" after each, or when you need the first edge that creates a cycle (Redundant Connection).

Match the pairs0/6 matched

Match the wording to the algorithm it points to.

Choose an item, then its match on the other side.
Quick check
In Rotting Oranges, every rotten orange spreads to its neighbours each minute. Why run one BFS with all rotten oranges in the queue, instead of one BFS per rotten orange?
Need a nudge? A hint rules out a wrong answer.

The decision routine

Put it in order5 steps

Put these decode questions in the order you should ask them.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

State complexity in terms of the graph: "O(V + E) for BFS or DFS, where V is the number of nodes and E the number of edges. On an n by m grid that is O(n · m)." Dijkstra with a binary heap is O(E log V). Union-find with path compression and union by rank is close to O(1) per operation.

Use the Decoder on graph problems and pay attention to the clue stage: most graph prompts hide the structure in story words like "rooms", "cities", or "accounts".

ChallengeMedium

Rotting Oranges

A crate is a grid where 0 is an empty slot, 1 is a fresh orange and 2 is a rotten one. Every minute, each rotten orange rots the fresh oranges directly above, below, left and right of it. Return the number of minutes until no fresh orange is left, or -1 if some fresh orange can never be reached.

[[2, 1, 1],
 [1, 1, 0],
 [0, 1, 1]]   →  4
 
[[2, 1, 1],
 [0, 1, 1],
 [1, 0, 1]]   →  -1   (bottom-left orange is cut off)
 
[[0, 2]]      →  0    (nothing fresh to begin with)

Constraints

  • 1 <= grid.length, grid[i].length <= 10
  • grid[i][j] is 0, 1 or 2
def oranges_rotting(grid: list[list[int]]) -> int: # Start a BFS from every rotten orange at once and count the layers. pass
ChallengeMedium

Course Schedule

There are num_courses courses labelled 0 to num_courses - 1. Each pair [a, b] in prerequisites means you must finish course b before course a. Return true if you can finish every course, and false if the requirements make that impossible.

num_courses = 2, prerequisites = [[1, 0]]          →  true
num_courses = 2, prerequisites = [[1, 0], [0, 1]]  →  false   (each needs the other)
num_courses = 3, prerequisites = []                →  true

Constraints

  • 1 <= num_courses <= 2000
  • 0 <= prerequisites.length <= 5000
  • 0 <= a, b < num_courses
def can_finish(num_courses: int, prerequisites: list[list[int]]) -> bool: # Build a graph and check whether it has a cycle. pass
Key terms
implicit graph
A graph you never get as edges, such as a grid of cells or words one letter apart.
multi-source BFS
BFS that starts with several nodes in the queue at distance 0, for simultaneous spreading.
topological sort
An order of a directed graph's nodes where every edge points forward. Exists only if there is no cycle.
union-find
A structure that merges groups and answers 'same group?' in near constant time.
Dijkstra
Shortest paths with non-negative weights, always expanding the cheapest known node using a min-heap.
O(V + E)
The cost of a full BFS or DFS: every node and every edge is handled once.