#310

Minimum Height Trees

Medium
Depth-First SearchBreadth-First SearchGraph TheoryTopological SortGraph TraversalBFS/DFSTree Properties
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a technique similar to finding the 'leaves' of the tree. By iteratively removing leaves, we can identify the nodes that will be the roots of the minimum height trees. This is efficient because it reduces the problem size quickly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create an adjacency list to represent the tree.
  2. 2Step 2: Initialize a queue with all leaf nodes (nodes with only one connection).
  3. 3Step 3: While there are more than two nodes, remove the leaves and update the graph.
  4. 4Step 4: The remaining nodes in the graph are the roots of the minimum height trees.
solution.py22 lines
1# Full working Python code
2from collections import defaultdict, deque
3
4def minHeightTrees(n, edges):
5    if n == 1:
6        return [0]
7    graph = defaultdict(list)
8    for u, v in edges:
9        graph[u].append(v)
10        graph[v].append(u)
11    leaves = deque([i for i in range(n) if len(graph[i]) == 1])
12    remaining_nodes = n
13    while remaining_nodes > 2:
14        size = len(leaves)
15        remaining_nodes -= size
16        for _ in range(size):
17            leaf = leaves.popleft()
18            for neighbor in graph[leaf]:
19                graph[neighbor].remove(leaf)
20                if len(graph[neighbor]) == 1:
21                    leaves.append(neighbor)
22    return list(leaves)

Complexity note: The time complexity is O(n) because we process each node and edge a limited number of times. The space complexity is O(n) due to the adjacency list and the queue used for leaves.

  • 1Minimum height trees can have one or two roots.
  • 2Removing leaves iteratively helps in finding the roots efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.