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.
时间: 2024-10-26 01:19:50