美文网首页
leetcode 310 最小高度树 python

leetcode 310 最小高度树 python

作者: DaydayHoliday | 来源:发表于2019-05-15 15:26 被阅读0次

    评论区说容易超时,就使用了字典和最小堆来进行加速

    import heapq
    class Solution(object):
        def findMinHeightTrees(self, n, edges):
            if n==1:
                return [0]
            dict_nei={}
            for e in edges:
                dict_nei[e[0]] = [e[1]] if e[0] not in dict_nei else dict_nei[e[0]]+[e[1]]
                dict_nei[e[1]] = [e[0]] if e[1] not in dict_nei else dict_nei[e[1]]+[e[0]]
            hq=[]
            for nei in dict_nei:
                heapq.heappush(hq,(len(dict_nei[nei]),nei,dict_nei[nei]))
            while len(dict_nei.keys())>=3:
                node_neis=[]
                while hq[0][0]==1:
                    _,node,neis=heapq.heappop(hq)
                    del dict_nei[node]
                    node_neis.append((node,neis))
                for node,neis in node_neis:
                    for nei in neis:
                        dict_nei[nei].remove(node)
                        heapq.heappush(hq,(len(dict_nei[nei]),nei,dict_nei[nei]))
            return dict_nei.keys()
    

    相关文章

      网友评论

          本文标题:leetcode 310 最小高度树 python

          本文链接:https://www.haomeiwen.com/subject/mawpaqtx.html