https://leetcode.com/problems/minimum-height-trees/
有trick
对graph不熟悉。再看几遍。
参考http://bookshadow.com/weblog/2015/11/26/leetcode-minimum-height-trees/
基本思路是“逐层删去叶子节点,直到剩下根节点为止”
有点类似于拓扑排序
最终剩下的节点个数可能为1或者2
时间复杂度:O(n),其中n为顶点的个数。
记住这些结论以及这样的code怎么写就行了。就跟拓扑排序一样,逐次去掉leaf node
class Solution(object):
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
children = collections.defaultdict(set)
for s, t in edges:#记录edge
children[s].add(t)
children[t].add(s)
vertices = set(children.keys())
while len(vertices) > 2:
leaves = [x for x in children if len(children[x]) == 1]
for x in leaves:
for y in children[x]:
children[y].remove(x)
del children[x]
vertices.remove(x)
return list(vertices) if n != 1 else [0]