Minimum Height Trees

Hard

Topics
GraphBFSTopological Sort

Given a tree of n nodes labeled from 0 to n-1 with n-1 edges, return the number of nodes that could be the root of a Minimum Height Tree (MHT). A MHT is one where the longest path from root to any leaf is minimized.

Example 1

0123
minimum-height root
Rooting the tree at a shaded node gives the smallest possible height. Those are the centres of the tree, found by repeatedly stripping all current leaves until one or two nodes remain — never more than two.
Nodes are drawn on a circle; an edge list says nothing about layout, only about connections.
Input:  n = 4, edges = [[1,0],[1,2],[1,3]]
Output: 1

Example 2

012345
minimum-height root
Input:  n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
Output: 2

Constraints

  • 1 <= n <= 2*10^4
  • edges.length == n - 1
  • The graph is a valid tree.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Rooting the tree at a node whose eccentricity is minimal is the definition of a centre, and a tree has exactly one or two of them. So the answer is never more than 2, which is worth saying before any code — it reframes the question from "compute n heights" to "find the centre".

Peel the tree from the outside. Remove all current leaves at once, then all the leaves of what remains, and so on. Each round strips one layer from every branch simultaneously, so the last one or two nodes standing are the deepest-buried, which is exactly the centre.

Two nodes survive when the tree's longest path has even length, one when it is odd — the centre is the middle of the diameter.

Approach

  1. Return 1 immediately for a single node.
  2. Build adjacency sets and collect every node of degree 1.
  3. While more than two nodes remain, remove the current leaf layer, unlink each from its neighbour, and collect the neighbours that have just become leaves.
  4. Return the count of nodes left standing.

Dry Run

n = 6   edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]

      0   1   2
       \  |  /
          3
          |
          4
          |
          5

degrees  [1, 1, 1, 4, 2, 1]

round 0  peel leaves [0, 1, 2, 5]   6 nodes before peeling, 2 after
         node 3 drops to degree 1, node 4 drops to degree 1

2 nodes remain, so the loop stops

final centres [3, 4]   answer 2

  n = 1 -> 1   a lone node is its own centre
  n = 2 -> 2   both ends of a single edge are centres

Complexity

  • Time — O(n): every node is peeled once and every edge is unlinked once.
  • Space — O(n) for the adjacency sets and the leaf frontier.

Common Pitfalls

  • Computing the height from every root with a separate BFS. That is O(n²) — 4×10⁸ operations at the stated bound — and it is the version the peel replaces.
  • Peeling one leaf at a time instead of a whole layer. The layers are what make the remaining nodes equidistant from the frontier; peeling individually can strand the wrong node.
  • Looping while more than one node remains. With an even-length diameter two centres are tied, and continuing removes one of them arbitrarily.
  • Forgetting the n == 1 case, where the node has degree 0 and is never collected as a leaf, so the frontier starts empty.
  • Using an adjacency list and deleting by value, which is O(degree) per removal and turns the peel into O(n²) on a star. Sets, or a degree counter, keep it linear.
  • Claiming the answer can exceed 2. It cannot — and an interviewer will ask you to justify that, which the diameter-midpoint argument does.

Full Solution — all languages

class Solution:
    def findMinHeightTreesCount(self, n, edges):
        if n == 1:
            return 1
        adj = [set() for _ in range(n)]
        for a, b in edges:
            adj[a].add(b)
            adj[b].add(a)
        leaves = [i for i in range(n) if len(adj[i]) == 1]
        remaining = n
        while remaining > 2:
            remaining -= len(leaves)
            nxt = []
            for leaf in leaves:
                neighbour = adj[leaf].pop()
                adj[neighbour].discard(leaf)
                if len(adj[neighbour]) == 1:
                    nxt.append(neighbour)
            leaves = nxt
        return len(leaves) if leaves else remaining
SensAI
Beta
Tap the mic to stop voice mode