Minimum Height Trees
Find the best roots of a tree by trimming its leaves layer by layer until one or two nodes remain.
The problem
You get a tree with n nodes labeled 0 to n - 1, given as a list of n - 1 undirected edges. Rooting the tree at a node gives it a height: the number of edges on the longest path from that root down to a leaf. Return every node that gives the smallest possible height, in any order.
Input n = 6, edges = [[0, 1], [1, 2], [2, 3], [3, 4], [2, 5]]
Output [2]
Rooted at 2, every node is at most 2 edges away. Any other root has a node 3 or more edges away.
Input n = 4, edges = [[0, 1], [1, 2], [2, 3]]
Output [1, 2]
The tree is a path of 4 nodes, so both middle nodes give height 2.
Key constraint: n can be 20,000, so computing the height from every possible root, O(n) each, means O(n^2) time and is too slow.
How to spot the pattern
- You need the center of a tree: the nodes whose farthest distance to any other node is as small as possible.
- Leaves are never the answer once the tree has three or more nodes, and removing them doesn't move the center.
The idea
The best roots sit in the middle of the tree's longest path, and a leaf is never in that middle once the tree has three or more nodes. Removing all current leaves at once leaves a smaller tree with the same middle, so keep peeling leaves layer by layer, like Kahn's algorithm with the degree in place of the indegree. When at most two nodes are left, they are the answer; there are two when the longest path has an even number of nodes.
Brute force: Run a BFS from every node to find its height and keep the nodes with the smallest one, which takes O(n^2) time.
Step by step
- 1If
nis 1, return[0]. - 2Build the neighbor lists and the degree of every node, and put every node of degree 1 (a leaf) in the first layer.
- 3While more than two nodes remain, remove the whole current layer of leaves.
- 4For each removed leaf, lower its neighbors' degrees, and put a neighbor in the next layer when its degree drops to 1.
- 5Return the nodes of the last layer.
See the pattern move
The topological sort pattern on a small example. Step through it, or press play.
Code
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n == 1:
return [0]
neighbors = [[] for _ in range(n)]
degree = [0] * n
for a, b in edges:
neighbors[a].append(b)
neighbors[b].append(a)
degree[a] += 1
degree[b] += 1
leaves = [v for v in range(n) if degree[v] == 1]
remaining = n
while remaining > 2:
remaining -= len(leaves) # peel off the whole layer at once
next_leaves = []
for leaf in leaves:
for nb in neighbors[leaf]:
degree[nb] -= 1
if degree[nb] == 1: # nb just became a leaf
next_leaves.append(nb)
leaves = next_leaves
return leavesComplexity
Time
O(n)
Space
O(n)
Each node is removed once and each edge is looked at from both ends; the neighbor lists hold 2(n - 1) entries.
Watch out for
- Forgetting
n = 1, where there are no edges and no leaves, and the answer is[0]. - Stopping only when one node is left: there can be two centers, so stop as soon as at most two remain.
- Removing leaves one at a time and stopping when two nodes are left: on the path 0, 1, 2, 3, 4 that can stop at 2 and 3, although the only center is 2.
Follow-up questions
Why can there be at most two answers?
The answers are the middle of a longest path in the tree. A path with an odd number of nodes has one middle node, and a path with an even number has two.
Can you find the center another way?
BFS from any node to the farthest node a, then BFS from a to the farthest node b while keeping parents. The middle one or two nodes of the path from a to b are the answer.
In Hinglish
Tree ke saare leaves ek saath hatao, phir naye bane leaves hatao, aise layer by layer. Jab ek ya do node bachein, wahi minimum height waale roots hain.