leetcode Minimum Height Trees

For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.node

Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).python

You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.app

Example 1:spa

Given n = 4edges = [[1, 0], [1, 2], [1, 3]]code

        0
        |
        1
       / \
      2   3

return [1]orm

Example 2:blog

Given n = 6edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]leetcode

     0  1  2
      \ | /
        3
        |
        4
        |
        5

return [3, 4]get

題意:it

給定一個n個結點n-1條邊的無向圖(就是樹啦),讓你找從哪一個點出發,到其餘結點的最長距離最小?(返回全部答案)

思路:

一開始相似RIP來更新距離,結果TLE。證實O(n^2)的複雜度太大

只好想其餘的方法。

答案必定是最長距離的中間結點位置上。

咱們要的是中間結點,沿着樹的外圍每次把葉子結點砍掉,那麼,最後剩下的不就是中間結點了麼?


# leetcode Minimum Height Trees
# http://www.hrwhisper.me/leetcode-minimum-height-trees/
class Solution(object):
    def findMinHeightTrees(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: List[int]
        """
        if n==1: return [0]

        digree = [0 for i in xrange(n)]
        g = [[] for i in xrange(n)]
        for x,y in edges:
            digree[x] += 1
            digree[y] += 1
            g[x].append(y) #add_edge
            g[y].append(x)

        leaves = [i for i in xrange(n) if digree[i]==1]
        nodes = n
        while nodes > 2:
            temp = []
            for i in leaves:
                digree[i] = 0
                nodes -= 1
                for j in g[i]:
                    digree[j] -= 1
                    if digree[j] == 1:
                        temp.append(j)
            leaves = temp
        return leaves

本文地址(就是個人新blog):http://www.hrwhisper.me/leetcode-minimum-height-trees/
本文由 hrwhisper 原創發佈,轉載請點名出處

相關文章
相關標籤/搜索