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.
Example 1:
Input: n = 4, edges = [[1,0],[1,2],[1,3]] Output: [1] Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
Example 2:
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]] Output: [3,4]
Example 3:
Input: n = 1, edges = [] Output: [0]
Example 4:
Input: n = 2, edges = [[0,1]] Output: [0,1]
方法:toplogical sort (类似course schedule,alien dictionary)
步骤:
1. 用一个map存放每一个node相邻的其他node。在example1中,即为{1:[0,2,3], 0:{1}, 2{1}, 3:{1}}
2. 找出所有只有一个相邻node的node,这样的node即为leaf。可以用一个array来存放全部的leaf。
3. 把n update成非leaf的数量,即 n = n - leaf_size.把leaf从它相邻的node的list中删去。如在example1中,把0从1的value的list中删去==> 1:{2,3} 操作后如果1的value的list变成了1,意味着此时的node也变成了leaf。构建一个新的array
来存放这样的leaf。
4. 使用一个while循环来重复3的步骤。while结束的条件是n <= 2. 最后剩下的leaf即为题目所求的root。
time complexity: O(n). space complexity: O(n)
class Solution: def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: if n == 1: return [0] adj = collections.defaultdict(list) for f, t in edges: adj[f].append(t) adj[t].append(f) leaves = [] for l in adj.keys(): if len(adj[l]) == 1: leaves.append(l) while n > 2: n -= len(leaves) newLeaves = [] for l in leaves: adjnodes = adj[l] for node in adjnodes: adj[node].remove(l) if len(adj[node]) == 1: newLeaves.append(node) leaves = newLeaves return leaves