class Solution(object):
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
#a graph has maxmimum 2 minimum height tree
#peel away the leaves one layer at a time until there are two or fewer nodes
if n==1: return [0]
adj=[set() for _ in range(n)]
for i,j in edges:
adj[i].add(j)
adj[j].add(i)
leaves=[i for i in xrange(n) if len(adj[i])==1]
while n>2:
n-=len(leaves)
new_leaves=[]
for leave in leaves:
j=adj[leave].pop()
adj[j].remove(leave)
if len(adj[j])==1:new_leaves.append(j)
leaves=new_leaves
return leaves
310. Minimum Height Trees
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- For a undirected graph with tree characteristics, we can ...
- For a undirected graph with tree characteristics, we can ...
- For a undirected graph with tree characteristics, we can ...
- p.p1For a undirected graph with tree characteristics, we ...
- 问题描述 For a undirected graph with tree characteristics, we...