310. Minimum Height Trees
310. Minimum Height Trees
方法一:
通过BFS找到最长的路径,返回中间的节点,找最长路径的方法:先从任意一点出发,找到最远的节点,然后从最远的节点开始,找最长的路径。
class Solution(object):
def findMinHeightTrees(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
import collections
adjacency = collections.defaultdict(list)
for i, j in edges:
adjacency[i].append(j)
adjacency[j].append(i)
seen = [False] * n
seen[0] = True
qu = [0]
lastNode = -1
while qu:
node = qu.pop(0)
lastNode = node
if node in adjacency and not all(seen):
for nextnode in adjacency[node]:
if seen[nextnode] == False:
seen[nextnode] = True
qu.append(nextnode)
seen = [False] * n
seen[lastNode] = True
qu = [[lastNode,[lastNode]]]
while qu:
node, path = qu.pop(0)
finalPath = path
if node in adjacency and not all(seen):
for nextnode in adjacency[node]:
if seen[nextnode] == False:
seen[nextnode] = True
qu.append([nextnode,path+[nextnode]])
m = len(finalPath)
return finalPath[(m-1)//2:m//2+1]
方法二
网友评论