Skip to content

Instantly share code, notes, and snippets.

@wushbin
Created March 24, 2020 18:24
Show Gist options
  • Select an option

  • Save wushbin/d0dcfa402699d7e74a57d713d8ff76b0 to your computer and use it in GitHub Desktop.

Select an option

Save wushbin/d0dcfa402699d7e74a57d713d8ff76b0 to your computer and use it in GitHub Desktop.
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