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]
看了答案写的算法,太菜超时了,但也是一种锻炼吧
# @param {Integer} n
# @param {Integer[][]} edges
# @return {Integer[]}
def find_min_height_trees(n, edges)
# 根据答案拓扑排序写的超时代码
return [0] if edges.size == 0
return [0,1] if edges.size == 1
degree_map = {}
ramainNodes = n
for edge in edges
degree_map[edge[0]] = degree_map[edge[0]] ? (degree_map[edge[0]] + 1) : 1
degree_map[edge[1]] = degree_map[edge[1]] ? (degree_map[edge[1]] + 1) : 1
end
preEdge = [[-1,-1],[-1,-1]]
while ramainNodes > 2
for node_no,degree in degree_map.select{|node_no,degree| degree == 1}
for i in 0...edges.size
if edges[i].include? node_no
degree_map[edges[i][0]] -= 1
degree_map[edges[i][1]] -= 1
preEdge[0] = preEdge[1]
preEdge[1] = edges[i]
edges[i] = [-1,-1]
end
end
ramainNodes -= 1
# break if ramainNodes <= 3
end
end
if ramainNodes == 1
return (preEdge[1].include? preEdge[0][0]) ? [preEdge[0][0]] : [preEdge[0][1]]
else
for edge in edges do return edge if edge[0] != -1 end
end
end