Lesson 7 of 8 · 50 min
Trees and graphs
Tree BFS/DFS, LCA, graph BFS/DFS, topological sort, clone graph, word ladder — with blast-radius and migration-order production metaphors.
BFS vs DFS is a product decision, not a taste
Key idea
Tree BFS: level order and right side view
1LEVEL ORDER — template for tree BFS23from collections import deque45def level_order(root):6 if not root:7 return []8 q = deque([root])9 out = []10 while q:11 level = []12 for _ in range(len(q)):13 node = q.popleft()14 level.append(node.val)15 if node.left: q.append(node.left)16 if node.right: q.append(node.right)17 out.append(level)18 return out1920# Right side view: last node in each level (or track right-first DFS with depth).Tree DFS: path sum and LCA sketch
1LCA OF BST — exploit ordering23def lca_bst(root, p, q):4 while root:5 if p.val < root.val and q.val < root.val:6 root = root.left7 elif p.val > root.val and q.val > root.val:8 root = root.right9 else:10 return root11 return None1213# O(h) time, O(1) space iterative — mention vs recursive O(h) stack.Graph: course schedule (topo) and clone
1COURSE SCHEDULE — Kahn topo; cycle ⇒ false23from collections import deque, defaultdict45def can_finish(num_courses: int, prereq: list[list[int]]) -> bool:6 graph = defaultdict(list)7 indeg = [0] * num_courses8 for a, b in prereq: # b -> a (b before a)9 graph[b].append(a)10 indeg[a] += 111 q = deque([i for i in range(num_courses) if indeg[i] == 0])12 seen = 013 while q:14 u = q.popleft()15 seen += 116 for v in graph[u]:17 indeg[v] -= 118 if indeg[v] == 0:19 q.append(v)20 return seen == num_courses2122# Production: migration order of services; cycle = deploy deadlock.1CLONE GRAPH — map original node -> clone23def clone_graph(node):4 if not node:5 return None6 mp = {}7 def dfs(n):8 if n in mp:9 return mp[n]10 copy = Node(n.val)11 mp[n] = copy12 for nei in n.neighbors:13 copy.neighbors.append(dfs(nei))14 return copy15 return dfs(node)1617# O(V+E). Bug: cloning without map → infinite recursion on cycles.Word ladder — BFS shortest transformation
Common mistake
“DFS with memo finds shortest path in unweighted graphs just as well.”
Common mistake
“Trees need visited sets too.”
Key idea
Word ladder mechanics and grid-as-graph
1WORD LADDER — BFS with pattern map (sketch)23from collections import defaultdict, deque45def ladder_length(begin: str, end: str, word_list: list[str]) -> int:6 if end not in word_list:7 return 08 buckets: dict[str, list[str]] = defaultdict(list)9 for w in word_list:10 for i in range(len(w)):11 buckets[w[:i] + "*" + w[i+1:]].append(w)12 q = deque([(begin, 1)])13 seen = {begin}14 while q:15 w, d = q.popleft()16 if w == end:17 return d18 for i in range(len(w)):19 for nei in buckets[w[:i] + "*" + w[i+1:]]:20 if nei not in seen:21 seen.add(nei)22 q.append((nei, d + 1))23 return 0Serialize and path problems — DFS discipline
Common mistake
“Any graph problem that mentions ‘path’ is DFS.”
Course Schedule / Graph overview style (NeetCode graph playlist)NeetCodeInterview prep
- 01“BFS vs DFS?” → layers/shortest unweighted → BFS; paths/subtrees/backtrack → DFS.
- 02“Course schedule?” → topo Kahn; if not all nodes processed, cycle.
- 03“Clone graph?” → map old→new; DFS or BFS; without map infinite loop.
- 04“Word ladder?” → BFS on word graph; each edge one letter change.
- 05“LCA BST vs binary tree?” → BST walk by value; tree needs postorder combine.
- 06“Complexity graph?” → O(V+E) time; space O(V) for queues/visited.
- 07“Serialize tree?” → preorder + null markers; or level order with nulls.
- 08“Production?” → blast radius BFS; migration topo; AST DFS; graph clone for configs.
- 09"Course schedule cycle?" -> Kahn processed < V, or DFS gray back-edge.
- 10"Clone graph key?" -> map original -> clone during BFS/DFS.
- 11"UF when?" -> dynamic connectivity, redundant edges, accounts merge, provinces.
- 12"Tree diameter?" -> two BFS or height DP; path through root vs subtrees.
- 13"Level-order trick?" -> snapshot len(q) before processing a level.
- 14"When BFS not Dijkstra?" -> unweighted (or equal weight) edges only.
Topo, union-find, and traversal spoken catalog
1COURSE SCHEDULE — Kahn topo (cycle => False)23from collections import deque, defaultdict45def can_finish(num_courses: int, prerequisites: list[list[int]]) -> bool:6 graph: dict[int, list[int]] = defaultdict(list)7 indeg = [0] * num_courses8 for a, b in prerequisites: # b -> a9 graph[b].append(a)10 indeg[a] += 111 q = deque([i for i in range(num_courses) if indeg[i] == 0])12 seen = 013 while q:14 u = q.popleft()15 seen += 116 for v in graph[u]:17 indeg[v] -= 118 if indeg[v] == 0:19 q.append(v)20 return seen == num_courses # incomplete => cycle; O(V+E)1UNION-FIND — path compression + union by rank23class DSU:4 def __init__(self, n: int):5 self.p = list(range(n))6 self.r = [0] * n78 def find(self, x: int) -> int:9 while self.p[x] != x:10 self.p[x] = self.p[self.p[x]]11 x = self.p[x]12 return x1314 def union(self, a: int, b: int) -> bool:15 ra, rb = self.find(a), self.find(b)16 if ra == rb:17 return False # redundant edge18 if self.r[ra] < self.r[rb]:19 ra, rb = rb, ra20 self.p[rb] = ra21 if self.r[ra] == self.r[rb]:22 self.r[ra] += 123 return True # ~O(alpha(n)) amortizedCommon mistake
"Tree and BST code are interchangeable."
Common mistake
"Graph DFS without visited is fine if the graph is small."
Key idea
Course Schedule — NeetCodeNeetCode
Union-Find — William FisetWilliam FisetarticleGraph cheatsheet — TIHTech Interview HandbookCheckpoint
Shortest transformation from word A to B in a dictionary (one letter per step). Algorithm?
Checkpoint
Service dependency graph, directed. Need deploy order so deps go first. Cycle possible. Tool?
Checkpoint
Clone graph complexity with V vertices E edges?
Checkpoint
Right side view of a binary tree — clean approach?
Checkpoint
Interviewer: min depth of binary tree. You DFS full height of both sides always. Issue?
Can you choose BFS/DFS/topo on a fresh prompt and implement clone graph without infinite recursion?
Takeaways
- BFS for layers and unweighted shortest paths; DFS for structure/paths.
- Topo (Kahn) for ordering with cycle detection.
- Clone = map old→new while traversing.
- Word ladder is BFS on an implicit graph.
- Always state O(V+E) and visited policy on graphs.
Next: DP, backtracking, and the capstone mock — LRU, token bucket, streaming median under the four-axis rubric.
Sources
Free to read · better with Enzo
Learn it with Enzo
Save your progress, answer the checkpoints, and let Enzo quiz you on what you just read.