My code:
public class Solution {
private int V;
private List<Set<Integer>> adj;
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
if (n == 1) {
return Collections.singletonList(0);
}
this.V = n;
adj = new ArrayList<Set<Integer>>();
for (int i = 0; i < V; i++) {
adj.add(new HashSet<Integer>());
}
for (int i = 0; i < edges.length; i++) {
adj.get(edges[i][0]).add(edges[i][1]);
adj.get(edges[i][1]).add(edges[i][0]);
}
List<Integer> leaves = new ArrayList<Integer>();
for (int i = 0; i < V; i++) {
if (adj.get(i).size() == 1) {
leaves.add(i);
}
}
while (n > 2) {
n -= leaves.size();
List<Integer> newLeaves = new ArrayList<Integer>();
for (Integer leaf : leaves) {
int temp = adj.get(leaf).iterator().next();
adj.get(temp).remove(leaf);
if (adj.get(temp).size() == 1) {
newLeaves.add(temp);
}
}
leaves = newLeaves;
}
return leaves;
}
}
这道题目我没做出来。
然后看了答案:
https://discuss.leetcode.com/topic/30572/share-some-thoughts/2
我也只是照着实现,并不懂真正的原理。
具体看着文章吧。
实现方法和 topological sort 类似。
Anyway, Good luck, Richardo!