内容:
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
.
这个思路实际上是一个 BFS 思路。和常见的从根节点进行 BFS 不同,这里从叶子节点开始进行 BFS。
所有入度(即相连边数)为 1 的节点即是叶子节点。找高度最小的节点,即找离所有叶子节点最远的节点,也即找最中心的节点。
找最中心的节点的思路很简单:
- 每次去掉当前图的所有叶子节点,重复此操作直到只剩下最后的根。
根据这个思路可以回答题目中的 [ hint : How many MHTs can a graph have at most? ],只能有一个或者两个最小高度树树根。证明省略。
public class Solution {
private int[] radius;
private int[][] height;
private int[][] htnode;
private List<Integer>[] graph;
private void find(int prev, int node) {
for(int next: graph[node]) {
if (next == prev) continue;
find(node, next);
if (height[next][0] + 1 > height[node][0]) {
height[node][0] = height[next][0] + 1;
htnode[node][0] = next;
}
}
for(int next: graph[node]) {
if (next == prev) continue;
if (next == htnode[node][0]) continue;
if (height[next][0] + 1 > height[node][1]) {
height[node][1] = height[next][0] + 1;
htnode[node][1] = next;
}
}
}
private void find(int prev, int node, int sum) {
radius[node] = Math.max(sum, height[node][0]);
for(int next: graph[node]) {
if (next == prev) continue;
if (next == htnode[node][0]) {
find(node, next, Math.max(sum+1, height[node][1]+1));
} else {
find(node, next, Math.max(sum+1, height[node][0]+1));
}
}
}
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
radius = new int[n];
height = new int[n][2];
htnode = new int[n][2];
graph = new List[n];
for(int i=0; i<n; i++) graph[i] = new ArrayList<>();
for(int[] edge: edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
find(-1, 0);
find(-1, 0, 0);
int min = Integer.MAX_VALUE;
for(int r: radius) min = Math.min(min, r);
List<Integer> roots = new ArrayList<>();
for(int i=0; i<radius.length; i++) {
if (radius[i] == min) roots.add(i);
}
return roots;
}
}