310. 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.
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).
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.
Example 1:
Given n = 4, edges = [[1, 0], [1, 2], [1, 3]]
return [1]
Example 2:
Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
return [3, 4]
Hint:
How many MHTs can a graph have at most?
Note:
(1) According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”
(2) The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

問題分析

參考了LeetCode的Disccuss
Hint: 答案只可能有一個或兩個節點。思路為依次刪除葉子節點,剩下的1/2個節點即為解。
速度問題:如果每次遍歷選出葉子節點,速度比較慢,可以每次刪除當前葉子節點時,將新的葉子節點記錄下來。

AC代碼

class Solution(object):
    def findMinHeightTrees(self, n, edges):
        """
        :type n: int
        :type edges: List[List[int]]
        :rtype: List[int]
        """
        if n == 1:
            return [0]
        neighbor = [set() for i in range(n)]
        for p,q in edges:
            neighbor[p].add(q)
            neighbor[q].add(p)
        
        leaves = [x for x in range(n) if len(neighbor[x]) == 1]

        while n > 2:
            n -= len(leaves)
            newLeaves = []
            for p in leaves:
                q = neighbor[p].pop()
                neighbor[q].remove(p)
                if len(neighbor[q]) == 1:
                    newLeaves.append(q)
            leaves = newLeaves
        return leaves

Runtime: 116 ms which beats 82.55% of Python submissions.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,779評論 0 33
  • 世界好奇妙,它將物以類聚,人以群分……形成七彩不同的“圈子”,周而復始的循環往復著! 它們看似都遵循...
    88蘭貓閱讀 564評論 0 4
  • 工作總結的開頭對于一份工作總結的整體而言非常重要。工作總結開頭怎么寫呢?若每年都是老生常談,永恒不變的格式,不免自...
    簡明估閱讀 2,189評論 0 19
  • 業界資深人,家具設計師+軟裝設計師 雙料 打算玩這個 有人賞臉么?小眾的垂直行業覆蓋
    紋物閱讀 259評論 0 1
  • 躺在床上 總感覺在風中行走 收割后的田野空曠而憂郁 厭倦雨...
    楊云濤閱讀 442評論 3 3