边工作边刷题:70天一遍leetcode: day 31-2
Minimum Height Trees
要点:这题实质是topological sort。重点是这是对无向图,和有向图的几点区别:
- 不需要indegree,因为无向图入度和出度是相同的,所以邻接点的个数就能表示。下一层某结点只需要从adjSet中删除当前层结点即可
- 因为至少有degree 1,所以要这个是下一层的选择条件
class Solution(object):
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
adjList = [set() for i in range(n)]
for e in edges:
adjList[e[0]].add(e[1])
adjList[e[1]].add(e[0])
q = []
for i in range(len(adjList)):
if len(adjList[i])==1 or len(adjList[i])==0:
q.append(i)
while q:
qnext = []
for i in range(len(q)):
for e in adjList[q[i]]:
adjList[e].remove(q[i])
if len(adjList[e])==1:
qnext.append(e)
if not qnext: return q
q=qnext
return []