***310. Minimum Height Trees [Medium] BFS

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]

方法二

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容