Tree as a Graph
What is this?
A tree normally only knows how to point downward โ every node knows its children but not its parent, like a one-way street. Some problems need you to travel up toward the parent as well, such as finding the nearest exit or how fast something spreads. The fix is simple: add links back up so every connection works both ways, turning the tree into a free-roaming map (a graph). Then you just explore it normally.
๐ก Fun fact: A tree is really just a graph with no loops, so adding parent links doesn't break anything โ it simply unlocks the full toolbox of graph techniques on the same data.
๐ The 2 problems in this chapter are free. Sign in with Google or Microsoft to start solving.
Core idea: A binary tree only stores child pointers โ you can go down, never up. The moment a problem lets you move toward the parent as well (nearest/farthest, time-to-spread), the tree's pointers aren't enough. The fix: add parent edges to make it an undirected graph, then run plain BFS. "I can move up" is the signal to convert.
The conversion
Build adjacency once (each node โ its children and its parent), then BFS from the source. The structure becomes a graph; the distance metric becomes ordinary BFS distance.
The problems
- Closest Leaf in a Binary Tree โ BFS from the target until the first leaf; the closest leaf may be reached by going up then down.
- Amount of Time for Binary Tree to Be Infected โ infection spreads to all neighbors each minute; the answer is the max graph distance from the start node.
Key takeaways
- Child-only pointers can't go up โ add parent edges to make the tree undirected.
- "Move toward the parent" / "spread to neighbors" โ tree-as-graph + BFS.
- Nearest = first BFS hit; farthest = last BFS level (eccentricity from the source).
- Build adjacency once, then the problem is a standard graph BFS.
- Why interviewers love it: it tests whether you recognize when a tree's own structure stops being enough.
Order: Closest Leaf in a Binary Tree โ Amount of Time for Binary Tree to Be Infected.