当前位置:网站首页>310. Minimum Height Trees
310. Minimum Height Trees
2022-06-22 12:26:00 【Sterben_Da】
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 * 104edges.length == n - 10 <= ai, bi < nai != 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边栏推荐
- 请问Flink的动态表是这样创建吗?我用flink cdc 读mysql数据,写flink动态表,发
- Tis tutorial 03 export
- Reddit product director: a practical guide for NFT members for Web3 creators
- Parallels Desktop 17.1.4pd虚拟机
- MySQL 5.7 + Navicat 下载安装教程(附安装包)
- The solution of VPC network automatic configuration based on terraform
- 342. Power of Four
- Gradle notes
- go语言笔记
- SAP 客户端中文显示乱码问题
猜你喜欢

Final of the 12th Blue Bridge Cup embedded design and development project

Reddit product director: a practical guide for NFT members for Web3 creators

帝云CMS升级PHP8注意事项

巨杉数据库荣获艾媒咨询2022年中国信创产业双项荣誉

MySQL_ Create and manage tables

SAP development keys application SSCR keys application

leetcode 11. 盛最多水的容器

On the routing tree of gin

Under Xinchuang: when the domestic database stars shine

Wisdom age voice +php
随机推荐
In C # development, the third-party components lambdaparser, dynamicexpresso and z.expressions are used to dynamically parse / evaluate string expressions
Tis tutorial 03 export
SAP 客户端中文显示乱码问题
mysql笔记
Maui uses Masa blazor component library
MySQL notes
Final of the 11th Blue Bridge Cup embedded design and development project
SAP ABAP ole core code
Windows system installs multiple MySQL versions (without uninstalling the original version), and the old and new versions are compatible.
SAP SPRO configure how to display the corresponding t-code
338. Counting Bits
leetcode LCP 10. 二叉树任务调度
2022-6-21os review group linking method
Shutter & flame - tankcombat game console development (I)
342. Power of Four
Sequoiadb distributed database may 2022 issue
Tis tutorial 04 client
PostGIS through St_ Dwithin retrieves elements within a certain distance
MySQL_ Query of data processing
Is the dynamic table of Flink created in this way? I use the flick CDC to read MySQL data, write the flick dynamic table, and send