The problem is to find the roots of the Minimum Height Trees (MHTs) in an undirected graph. A minimum height tree is a tree whose root results in a tree with the minimum possible height.
Given an undirected graph with n
nodes labeled from 0
to n-1
, and a list of edges where edges[i] = [ai, bi]
indicates that there is an undirected edge between nodes ai
and bi
, you are required to return a list of all MHTs root labels.
An MHT is defined as a tree whose height is minimized.
Here’s the given constraints:
[0, n-1]
edges[i].length == 2
0 ≤ a_i, b_i < n
a_i != b_i
(a_i, b_i)
are distinct.Assuming answers:
n == 1
), return [0]
.This approach runs in O(n) time since each edge and node is processed once.
from collections import deque, defaultdict
def findMinHeightTrees(n, edges):
if n == 1:
return [0]
# Build the graph with adjacency list
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
# Initialize the first layer of leaves
leaves = [i for i in range(n) if len(graph[i]) == 1]
# Trim the leaves until reaching the centroids
remaining_nodes = n
while remaining_nodes > 2:
remaining_nodes -= len(leaves)
new_leaves = []
while leaves:
leaf = leaves.pop()
neighbor = graph[leaf].pop()
graph[neighbor].remove(leaf)
if len(graph[neighbor]) == 1:
new_leaves.append(neighbor)
leaves = new_leaves
return leaves
# Example usage:
print(findMinHeightTrees(4, [[1,0],[1,2],[1,3]])) # Should return [1]
print(findMinHeightTrees(6, [[3,0],[3,1],[3,2],[3,4],[5,4]])) # Should return [3, 4]
This method uses a breadth-first search (BFS) like technique tailored to find the centroids of the tree. By repeatedly removing the external layers of the tree (leaf nodes), we eventually narrow down to the central nodes that are the roots of the Minimum Height Trees.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?