Leetcode - Minimum Height Trees

My code:


public class Solution {
    private int V;
    private List> adj;
    public List findMinHeightTrees(int n, int[][] edges) {
        if (n == 1) {
            return Collections.singletonList(0);
        }
        this.V = n;
        adj = new ArrayList>();
        for (int i = 0; i < V; i++) {
            adj.add(new HashSet());
        }
        
        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 leaves = new ArrayList();
        for (int i = 0; i < V; i++) {
            if (adj.get(i).size() == 1) {
                leaves.add(i);
            }
        }
        
        while (n > 2) {
            n -= leaves.size();
            List newLeaves = new ArrayList();
            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!

你可能感兴趣的:(Leetcode - Minimum Height Trees)