Minimum Height Trees
Master this topic with zero to advance depth.
Minimum Height Trees
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.
For a tree of nodes, you can choose any node as the root. The height of the tree is the maximum distance between the root and any leaf.
Return a list of all MHTs' root labels.
Visual Representation
n = 4, edges = [[1, 0], [1, 2], [1, 3]]
0
|
1
/ \n2 3
Root 1 has height 1. Other roots have height 2.
Result: [1]Examples
Root 1 gives the minimum height tree.
Level I: Brute Force (DFS/BFS from every node)
Intuition
To find the root that minimizes height, we can treat every node as the root one-by-one, perform a BFS/DFS to find its height, and pick the minimum.
Thought Process
- For each node from to :
- Start a BFS/DFS from .
- Find the maximum distance from to any other node (this is the height).
- Record the height of each node. Find the minimum height.
- Return all nodes that produce this minimum height.
Why it's inefficient
For each of the nodes, we traverse elements. This leads to complexity.
Detailed Dry Run
n=3, edges=[[0,1],[1,2]]
- Root 0: Height 2 (path 0-1-2)
- Root 1: Height 1 (paths 1-0, 1-2)
- Root 2: Height 2 (path 2-1-0) Min Height: 1. Result: [1]
Level III: Optimal (Leaf Removal - BFS)
Intuition
The center of a tree is limited to 1 or 2 nodes. If we continuously remove the 'outer layers' (leaves), we will eventually converge on the center. This is similar to Kahn's algorithm but for undirected trees.
Thought Process
- Use an adjacency list and calculate the
degreeof each node. - Add all nodes with
degree == 1to a Queue (initial leaves). - In a loop, while
remainingNodes > 2:- Subtract current leaves count from
remainingNodes. - For each leaf in the queue:
- Pop it, find its only neighbor
nbr. - Decrement
degree[nbr]. - If
degree[nbr]becomes 1, addnbrto the next level queue.
- Pop it, find its only neighbor
- Subtract current leaves count from
- The final remaining nodes in the queue are the roots of MHTs.
Pattern: Topological Trimming
Detailed Dry Run
n=4, edges=[[1,0],[1,2],[1,3]]
- Degrees: {0:1, 1:3, 2:1, 3:1}. Leaves: [0, 2, 3]
- remainingNodes = 4. 4 > 2 is true.
- Remove 0,2,3. Neighbors: 1's degree 3->0. But we only decrement once for each leaf.
- 1's degree becomes 0. Queue empty. Result: [1]
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.