310. Minimum Height Trees
Medium
5332220Add to ListShare
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]
Constraints:
1 <= n <= 2 * 104
edges.length == n - 1
0 <= ai, bi < n
ai != bi
- All the pairs
(ai, bi)
are distinct. - The given input is guaranteed to be a tree and there will be no repeated edges.
超时:
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""
assert Solution().findMinHeightTrees(1, []) == [0]
assert Solution().findMinHeightTrees(4, [[1, 0], [1, 2], [1, 3]]) == [1]
assert Solution().findMinHeightTrees(6, [[3, 0], [3, 1], [3, 2], [3, 4], [5, 4]]) == [3, 4]
解题思路:题目保证为一棵树非联通图,依次对每个节点进行bfs,计算最长树高,最后遍历所有节点将结果存入数组
"""
# 广度优先计算当前节点的最大树高
def bfs(node: int):
# 相邻节点
nodeList = list(nodeEdge[node])
flag = set()
flag.add(node)
h = 0
while len(nodeList) > 0:
length = len(nodeList)
h += 1
while length > 0:
length -= 1
curNode = nodeList.pop(0)
flag.add(curNode)
for nextNode in nodeEdge[curNode]:
if flag.__contains__(nextNode):
# 遍历过了
continue
flag.add(nextNode)
nodeList.append(nextNode)
nodeH[node] = max(nodeH[node], h)
# 节点下标连接的边
nodeEdge = [[] for i in range(n)]
for edge in edges:
nodeEdge[edge[0]].append(edge[1])
nodeEdge[edge[1]].append(edge[0])
# 下标节点作为根节点最小的树高,初始0代表未初始化,题目保证是一棵树
nodeH = [0] * n
minH = sys.maxsize
for i in range(n):
bfs(i)
minH = min(minH, nodeH[i])
result = []
for i in range(n):
if nodeH[i] == minH:
result.append(i)
return result
正解:
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
"""
assert Solution().findMinHeightTrees(1, []) == [0]
assert Solution().findMinHeightTrees(4, [[1, 0], [1, 2], [1, 3]]) == [1]
assert Solution().findMinHeightTrees(6, [[3, 0], [3, 1], [3, 2], [3, 4], [5, 4]]) == [3, 4]
解题思路:题目保证为一棵树无环,对每个节点开始搜索会超时。
参考别人的:拓扑排序,每次将叶子节点(入度为1)加入队列,执行连接节点删边。重复上面操作。
直到最后一次把节点删完队列为空,这次删除的节点就是MHTs
理解:每次从最外围删除叶子节点,相当于从最远的地方开始bfs剪枝,因为 h(叶子->根->(叶子)) >= h(根->叶子)
最后一批叶子节点即为MHTs的根节点,因为到其他节点存在最短距离
"""
if n == 1:
return [0]
# 节点入度
indegree = [0] * n
# 节点下标连接的边
nodeEdge = [[] for i in range(n)]
for edge in edges:
nodeEdge[edge[0]].append(edge[1])
nodeEdge[edge[1]].append(edge[0])
indegree[edge[0]] += 1
indegree[edge[1]] += 1
# 叶子节点队列
leafNodes = []
for index in range(n):
if indegree[index] == 1:
leafNodes.append(index)
# 拓扑排序
result = []
while len(leafNodes) > 0:
result = list(leafNodes)
num = len(leafNodes)
while num > 0:
num -= 1
node = leafNodes.pop(0)
for nextNode in nodeEdge[node]:
indegree[nextNode] -= 1
if indegree[nextNode] == 1:
leafNodes.append(nextNode)
return result