Created
March 24, 2020 18:24
-
-
Save wushbin/d0dcfa402699d7e74a57d713d8ff76b0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public List<Integer> findMinHeightTrees(int n, int[][] edges) { | |
| Set<Integer>[] graph = new Set[n]; | |
| for (int i = 0; i < n; i++) { | |
| graph[i] = new HashSet<>(); | |
| } | |
| for (int[] edge : edges) { | |
| graph[edge[0]].add(edge[1]); | |
| graph[edge[1]].add(edge[0]); | |
| } | |
| List<Integer> queue = new LinkedList<>(); | |
| for (int i = 0; i < n; i++) { | |
| if (graph[i].size() <= 1) { | |
| queue.add(i); | |
| } | |
| } | |
| while(n > 2) { | |
| List<Integer> queue2 = new LinkedList<>(); | |
| for (int i : queue) { | |
| n -= 1; | |
| for(int next : graph[i]) { | |
| graph[next].remove(i); | |
| if (graph[next].size() == 1) { | |
| queue2.add(next); | |
| } | |
| } | |
| } | |
| queue.clear(); | |
| queue = queue2; | |
| } | |
| return queue; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment