mediumGraphBFSGraphs

Minimum Height Trees

mediumTime: O(V+E)Space: O(V+E)

Recognize the pattern

find nodes that minimize tree heightcentroids of the treepeel leaves inward

Brute force idea

The naive version of Minimum Height Trees sounds like this: Root the tree at each node, compute height, find minimum. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The real unlock in Minimum Height Trees comes when you notice this: Topological peeling: repeatedly remove leaf nodes (degree 1) layer by layer, like peeling an onion. The last 1-2 nodes remaining are the centroids (minimum height tree roots). Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Minimum Height Trees is this: The centroid(s) of a tree are the 1-2 nodes at the very center. Removing leaves brings you closer to the center. The process terminates with 1 or 2 remaining nodes. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

The trap in Minimum Height Trees usually looks like this: Not handling the case of exactly 2 remaining nodes — a tree can have 1 or 2 centroids. Both are valid answers. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Graphs Pattern