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]]
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/