Minimum Height Trees

You are given an undirected tree with n nodes labelled 0 to n - 1, described by a list edges where edges[i] = [a, b] connects nodes a and b. The edges are guaranteed to form a tree: the graph is connected and has no cycles.

Any node can be picked up and treated as the root. The height of the resulting rooted tree is the number of edges on the longest path from the root down to a leaf.

Return the labels of every node that, when chosen as the root, gives the smallest possible height. The labels may be returned in any order.

Example 1

Input: n = 5, edges = [[0,3],[1,3],[3,2],[4,3]] Output: [3] Why: Node 3 touches every other node, so rooting there gives height 1; any other root gives height 2.

Example 2

Input: n = 6, edges = [[0,1],[1,2],[2,3],[3,4],[4,5]] Output: [2,3] Why: The tree is a path with 5 edges, so its two middle nodes, 2 and 3, both give height 3.

Example 3

Input: n = 1, edges = [] Output: [0] Why: A single node is its own root with height 0.

Constraints

  • 1 <= n <= 2 · 104
  • edges.length == n - 1
  • 0 <= a, b < n and a != b
  • All pairs are distinct and the edges form a tree

Pattern Path · Graphs: Ordering & Union-Find · problem 141 of 169

Trying every node as a root and running a BFS from each is O(n²). What do the best roots have in common?
The best root sits in the middle of the longest path in the tree. Leaves are never good roots unless n is at most 2.
Peel the tree like an onion: remove all current leaves at once, which creates new leaves, and repeat. Whatever is left when at most two nodes remain is the answer.
Target: O(n) time, O(n) extra space.

Start simple

Run a BFS from every node to measure the height with that node as root and keep the minimum: O(n²) time.

The key idea

The height of a tree rooted at r is the distance from r to the farthest node. The farthest node from anywhere lies at one end of a longest path (the diameter) of the tree, so the best root is the node, or pair of adjacent nodes, in the exact middle of that path. A diameter with an even number of edges has one middle node; an odd one has two.

Finding that middle directly is fiddly, so peel the tree instead. Put every leaf (degree 1) in a queue and remove them all in one round, decrementing their neighbours' degrees. Neighbours whose degree drops to 1 become the next round's leaves. Each round shortens every longest path by one edge at each end, so the centre is never removed early, and it is all that remains when at most two nodes are left.

This is Kahn's topological-sort idea applied to an undirected tree, working from the outside in. Each node and edge is processed a constant number of times, so the whole process is linear.

Handle n == 1 separately: there are no edges and node 0 is the answer.

Complexity

  • Time: O(n)
  • Space: O(n)

Python

class Solution:
    def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
        if n <= 2:
            return list(range(n))

        neighbours = [set() for _ in range(n)]
        for a, b in edges:
            neighbours[a].add(b)
            neighbours[b].add(a)

        leaves = [node for node in range(n) if len(neighbours[node]) == 1]
        remaining = n
        # Peel off one whole layer of leaves at a time until the centre is left.
        while remaining > 2:
            remaining -= len(leaves)
            next_leaves = []
            for leaf in leaves:
                parent = neighbours[leaf].pop()
                neighbours[parent].remove(leaf)
                if len(neighbours[parent]) == 1:
                    next_leaves.append(parent)
            leaves = next_leaves
        return leaves

JavaScript

var findMinHeightTrees = function(n, edges) {
  if (n <= 2) return Array.from({ length: n }, (_, i) => i);

  const neighbours = Array.from({ length: n }, () => new Set());
  for (const [a, b] of edges) {
    neighbours[a].add(b);
    neighbours[b].add(a);
  }

  let leaves = [];
  for (let node = 0; node < n; node++) {
    if (neighbours[node].size === 1) leaves.push(node);
  }
  let remaining = n;
  // Peel off one whole layer of leaves at a time until the centre is left.
  while (remaining > 2) {
    remaining -= leaves.length;
    const nextLeaves = [];
    for (const leaf of leaves) {
      const [parent] = neighbours[leaf];
      neighbours[leaf].delete(parent);
      neighbours[parent].delete(leaf);
      if (neighbours[parent].size === 1) nextLeaves.push(parent);
    }
    leaves = nextLeaves;
  }
  return leaves;
};

What the interviewer is checking

The interviewer is looking for the insight that the answer is the centre of the tree, and for a clean layer-by-layer leaf-trimming BFS rather than n separate searches.

Mistakes to avoid

  • Forgetting the single-node case, where there are no edges and no leaves of degree 1.
  • Stopping when one node is left instead of when at most two are left; the answer can have two nodes.
  • Removing leaves one at a time instead of a whole layer at a time, which can strip the wrong side first.

Follow-ups to expect

  • Can there ever be three answers? (No: a diameter's middle is one or two nodes.)
  • How would you find the diameter itself? (Two BFS passes from any node.)
  • What if edges had weights? (Centre on weighted diameter; trim by distance.)

In real software

Choosing where to place a server, hub or root switch in a tree-shaped network so that the worst-case hop count to any node is as small as possible is exactly this problem.

Practice next

Next Post Previous Post
No Comment
Add Comment
comment url