Skip to content
Problem 310 · LeetCode 310(opens in a new tab)

Minimum Height Trees

MediumBreadth-first search

You are given a tree with n nodes, labelled 0 to n − 1, as a list of undirected edges. Any node can be picked as the root. Once rooted, the tree's height is how many edges you cross going from the root to the deepest leaf.

Return every node that gives the smallest possible height, in any order.

Example 1

Input:  n = 6, edges = [[0, 1], [1, 2], [1, 3], [3, 4], [4, 5]]
Output: [3]
Why:    from 3, every node is at most 2 edges away
2 more examples and the constraints

Example 2

Input:  n = 4, edges = [[0, 1], [1, 2], [2, 3]]
Output: [1, 2]
Why:    a path of 4 has two middle nodes, both height 2

Example 3

Input:  n = 1, edges = []
Output: [0]
Why:    the single node is the only choice

Constraints

  • 1 ≤ n ≤ 20,000
  • edges has n − 1 pairs [a, b] with a ≠ b and 0 ≤ a, b < n
  • The edges form a tree: connected, no repeated edges, no cycles

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. BFS from every rootO(n²)
  2. Trim leaves layer by layerO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 20,000 nodesVerdict
BFS from every rootO(n²)
Correct; too slow for 20,000 nodes
Trim leaves layer by layerO(n)
Best; each node trimmed once

n = number of nodes; a tree has n − 1 edges.

Edge cases to test

  • One node. n = 1 with no edges: return [0]. No node has degree 1, so handle it first.
  • Two nodes. Both are leaves and both are answers: [0, 1].
  • Star. One round trims every outer node and leaves the hub.
  • Even-length path. A path of 4 nodes has two centres, and both must be returned.

Common mistakes

  • Stopping when the leaf list is empty instead of when 2 or fewer nodes remain, which trims the answer away.
  • Trimming a leaf without lowering its neighbour's degree, so new leaves are never found.
  • Forgetting n = 1 (no edges, no leaves) and returning an empty list.

How to talk through it

  1. 1Clarify. Is it always a tree? Can n be 1? Any order for the answer?
  2. 2Give the brute force. BFS from every node for its height: O(n²), too slow for 20,000.
  3. 3Find the centre. The best root is the middle of the longest path; there are one or two such nodes.
  4. 4Code the trimming. Peel degree-1 nodes layer by layer, lowering degrees as you go, until at most 2 remain.
  5. 5Test out loud. Run n = 1, n = 2, a star and a path of 4.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?