題目:
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]]
0 | 1 / \ 2 3
return [1]
Example 2:
Given n = 6
, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2 \ | / 3 | 4 | 5
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.
鏈接: http://leetcode.com/problems/minimum-height-trees/
題解:
求給定圖中,能形成樹的最矮的樹。第一直覺就是BFS,跟Topological Sorting的Kahn方法很類似,利用無向圖每個點的degree來計算。但是卻后繼無力,於是還是參考了Discuss中Dietpepsi和Yavinci大神的代碼。
方法有兩種,一種是先計算每個點的degree,然后將degree為1的點放入list或者queue中進行計算,把這些點從neighbours中去除,然后計算接下來degree = 1的點。最后剩下1 - 2個點就是新的root
另外一種是用了類似給許多點,求一個點到其他點距離最短的原理。找到最長的一點leaf to leaf path,然后找到這條path的一個或者兩個中點median就可以了。
下面是用第一種方法做的。
Time Complexity - O(n), Space Complexity - O(n)
public class Solution { public List<Integer> findMinHeightTrees(int n, int[][] edges) { List<Integer> leaves = new ArrayList<>(); if(n <= 1) { return Collections.singletonList(0); } Map<Integer, Set<Integer>> graph = new HashMap<>(); // list of edges to Ajacency Lists for(int i = 0; i < n; i++) { graph.put(i, new HashSet<Integer>()); } for(int[] edge : edges) { graph.get(edge[0]).add(edge[1]); graph.get(edge[1]).add(edge[0]); } for(int i = 0; i < n; i++) { if(graph.get(i).size() == 1) { leaves.add(i); } } while(n > 2) { n -= leaves.size(); List<Integer> newLeaves = new ArrayList<>(); for(int leaf : leaves) { for(int newLeaf : graph.get(leaf)) { graph.get(leaf).remove(newLeaf); graph.get(newLeaf).remove(leaf); if(graph.get(newLeaf).size() == 1) { newLeaves.add(newLeaf); } } } leaves = newLeaves; } return leaves; } }
題外話:
今天下午得知群里好幾個都是caltech的大神...拜一拜,拜一拜
二刷:
兩種方法,一種是無向圖中求longest path,假如longest path長度是奇數,則結果為最中間的一個節點,否則為最中間的兩個節點。思路好想到,但是並不好寫。求Longest Path是一個NP-Hard問題。但對於DAG來說可以用dp來求出結果。這里un-directed graph我們也可以試一試。
另一種方法是用BFS類似Topological Sorting中的Kahn方法。先計算每個節點的degree,然后把低degree的節點leaf放入queue中進行處理,一層一層把低degree節點逐漸剝離,最后剩下的1 - 2個節點就是解。
Java:
超時的longest path找中點
Time Complexity - O(n2), Space Complexity - O(n) <- TLE
public class Solution { public List<Integer> findMinHeightTrees(int n, int[][] edges) { List<Integer> res = new ArrayList<>(); if (edges == null || edges.length == 0 || edges.length != n - 1) return res; List<LinkedList<Integer>> paths = new ArrayList<>(); // no cycle, no duplicate int len = 0, maxIndex = 0; for (int[] edge : edges) { for (int i = 0; i < paths.size(); i++) { LinkedList<Integer> path = paths.get(i); if (path.peekFirst() == edge[0]) path.addFirst(edge[1]); else if (path.peekFirst() == edge[1]) path.addFirst(edge[0]); else if (path.peekLast() == edge[0]) path.addLast(edge[1]); else if (path.peekLast() == edge[1]) path.addLast(edge[0]); if (paths.get(i).size() > len) { len = paths.get(i).size(); maxIndex = i; } } paths.add(new LinkedList<>(Arrays.asList(new Integer[] {edge[0], edge[1]}))); } LinkedList<Integer> longestPath = paths.get(maxIndex); if (longestPath.size() % 2 == 0) { res.add(longestPath.get(longestPath.size() / 2 - 1)); res.add(longestPath.get(longestPath.size() / 2)); } else { res.add(longestPath.get(longestPath.size() / 2)); } return res; } }
參考樂神和Yavinci的remove leaf:
跟一刷一樣。先計算degree為1的節點,這些節點只和一個節點相連,所以這些是leaf節點。逐個去除掉leaf節點以后我們可以嘗試計算上一層leaf,繼續and繼續,直到最后我們剩下一個節點或者兩個節點,就是我們要求的root nodes。
Time Complexity - O(n), Space Complexity - O(n)
public class Solution { public List<Integer> findMinHeightTrees(int n, int[][] edges) { List<Integer> leaves = new ArrayList<>(); if (n == 1) return Collections.singletonList(0); List<Set<Integer>> graph = new ArrayList<>(); for (int i = 0; i < n; i++) graph.add(new HashSet<>()); for (int[] edge : edges) { graph.get(edge[0]).add(edge[1]); graph.get(edge[1]).add(edge[0]); }for (int i = 0; i < n; i++) { if (graph.get(i).size() == 1) leaves.add(i); } while (n > 2) { n -= leaves.size(); List<Integer> newLeaves = new ArrayList<>(); for (int leaf : leaves) { for (int j : graph.get(leaf)) { graph.get(j).remove(leaf); if (graph.get(j).size() == 1) newLeaves.add(j); } } leaves = newLeaves; } return leaves; } }
Reference:
https://leetcode.com/discuss/71763/share-some-thoughts
https://leetcode.com/discuss/71738/easiest-75-ms-java-solution
https://leetcode.com/discuss/73926/share-java-using-degree-with-explanation-which-beats-more-than
https://leetcode.com/discuss/71656/c-solution-o-n-time-o-n-space
https://leetcode.com/discuss/72739/two-o-n-solutions
https://leetcode.com/discuss/71804/java-layer-by-layer-bfs
https://leetcode.com/discuss/71721/iterative-remove-leaves-python-solution
https://leetcode.com/discuss/71802/solution-share-midpoint-of-longest-path
https://leetcode.com/discuss/73926/share-java-using-degree-with-explanation-which-beats-more-than
https://leetcode.com/discuss/71676/share-my-accepted-solution-java-o-n-time-o-n-space
https://discuss.codechef.com/questions/51180/finding-longest-path-in-an-undirected-and-unweighted-graph
http://cs.nyu.edu/courses/spring14/CSCI-UA.0480-004/Lecture14.pdf
http://www.geeksforgeeks.org/find-longest-path-directed-acyclic-graph/