[Swift]LeetCode310. 最小高度樹 | Minimum Height Trees
For an 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]
[1, 0]
and thus will not appear together in edges
.
Example 1 :
Input:n = 4
,edges = [[1, 0], [1, 2], [1, 3]]
0 | 1 / \ 2 3 Output:[1]
Example 2 :
Input:n = 6
,edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2 \ | / 3 | 4 | 5 Output:[3, 4]
Note:
- 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.”
- The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
對於一個具有樹特徵的無向圖,我們可選擇任何一個節點作為根。圖因此可以成為樹,在所有可能的樹中,具有最小高度的樹被稱為最小高度樹。給出這樣的一個圖,寫出一個函式找到所有的最小高度樹並返回他們的根節點。
格式
該圖包含 n
個節點,標記為 0
到 n - 1
。給定數字 n
和一個無向邊 edges
列表(每一個邊都是一對標籤)。
你可以假設沒有重複的邊會出現在 edges
中。由於所有的邊都是無向邊, [0, 1]
和 [1, 0]
是相同的,因此不會同時出現在 edges
裡。
示例 1:
輸入:n = 4
,edges = [[1, 0], [1, 2], [1, 3]]
0 | 1 / \ 2 3 輸出:[1]
示例 2:
輸入:n = 6
,edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2 \ | / 3 | 4 | 5 輸出:[3, 4]
說明:
- 根據樹的定義,樹是一個無向圖,其中任何兩個頂點只通過一條路徑連線。 換句話說,一個任何沒有簡單環路的連通圖都是一棵樹。
- 樹的高度是指根節點和葉子節點之間最長向下路徑上邊的數量。
1724 ms
1 class Solution { 2 func findMinHeightTrees(_ n: Int, _ edges: [[Int]]) -> [Int]{ 3 var graph = [Int : Set<Int>]() 4 for edge in edges { 5 if graph[edge[0]] == nil { 6 graph[edge[0]] = [edge[1]] 7 }else { 8 graph[edge[0]]!.insert(edge[1]) 9 } 10 if graph[edge[1]] == nil { 11 graph[edge[1]] = [edge[0]] 12 }else { 13 graph[edge[1]]!.insert(edge[0]) 14 } 15 16 } 17 while graph.count > 2 { 18 let list = graph.filter{$1.count == 1} 19 for dict in list { 20 graph[dict.value.first!]?.remove(dict.key) 21 graph[dict.key] = nil 22 } 23 } 24 25 let res = Array(graph.keys) 26 if res.isEmpty { 27 return [0] 28 } 29 return res 30 } 31 }