Minimum Height Trees

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Minimum Height Trees相关的知识,希望对你有一定的参考价值。

 1 public class Solution {
 2     public List<Integer> findMinHeightTrees(int n, int[][] edges) {
 3         if (n == 1) {
 4             return Collections.singletonList(0);
 5         }
 6         Map<Integer, Set<Integer>> nodes = new HashMap<>();
 7         for (int i = 0; i < n; i++) {
 8             nodes.put(i, new HashSet<>());
 9         }
10         for (int[] edge : edges) {
11             nodes.get(edge[0]).add(edge[1]);
12             nodes.get(edge[1]).add(edge[0]);
13         }
14         
15         List<Integer> leaves = new ArrayList<>();
16         for (Integer i : nodes.keySet()) {
17             if (nodes.get(i).size() == 1) {
18                 leaves.add(i);
19             }
20         }
21         
22         while (n > 2) {
23             n -= leaves.size();
24             List<Integer> newLeaves = new ArrayList<>();
25             for (int leave : leaves) {
26                 int current = nodes.get(leave).iterator().next();
27                 nodes.get(current).remove(leave);
28                 if (nodes.get(current).size() == 1) {
29                     newLeaves.add(current);
30                 }
31             }
32             leaves = newLeaves;
33         }
34         return leaves;
35     }
36 }

1. Check boundary case that when n == 1. There is only one node (0)

2. Set can access by iterator.

以上是关于Minimum Height Trees的主要内容,如果未能解决你的问题,请参考以下文章

310. Minimum Height Trees

310. Minimum Height Trees

310. Minimum Height Trees

310. Minimum Height Trees

Minimum Height Trees 解答

leetcode@ [310] Minimum Height Trees