1 public class Solution { 2 public ListfindMinHeightTrees(int n, int[][] edges) { 3 if (n == 1) { 4 return Collections.singletonList(0); 5 } 6 Map > 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 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 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.