Minimum Height Trees
Last updated
Was this helpful?
Last updated
Was this helpful?
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.
Given a tree of n
nodes labelled from 0
to n - 1
, and an array of n - 1
edges
where edges[i] = [ai, bi]
indicates that there is an undirected edge between the two nodes ai
and bi
in the tree, you can choose any node of the tree as the root. When you select a node x
as the root, the result tree has height h
. Among all possible rooted trees, those with minimum height (i.e. min(h)
) are called minimum height trees (MHTs).
Return a list of all MHTs' root labels. You can return the answer in any order.
The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
As the hints suggest, this problem is related to the data structure. Moreover, it is closely related to the problems of and . This relationship is not evident, yet it is the key to solve the problem, as one will see later.
The first step we describe above is actually the problem of , which is to find the maximum distance from the root to the leaves nodes. For this, we can either apply the (DFS) or (BFS) algorithms.
As a spoiler alert, in this article, we will present a alike algorithm with time complexity of O(n), which is also the algorithm to solve the well-known course schedule problems.