classSolution{publicList<Integer>findMinHeightTrees(int n,int[][] edges){// Base caseList<Integer> list =newArrayList<>();if(edges.length ==0){
list.add(0);return list;}// Indegree of every nodeint[] indegree =newint[n];// save adjacent nodes of certain node into a HashMapHashMap<Integer,ArrayList<Integer>> map =newHashMap<>();for(int i =0; i < n; i++) map.put(i,newArrayList<>());// Build degree counts and neighbors of each nodefor(int[] edge : edges){
indegree[edge[0]]++;
indegree[edge[1]]++;
map.get(edge[0]).add(edge[1]);
map.get(edge[1]).add(edge[0]);}// if indegree of a node is 1, it means that the node only has one adjacent node Queue<Integer> q =newLinkedList<>();for(int i =0; i < n; i++)if(indegree[i]==1) q.offer(i);// count the number of nodes which has been watchedint count =0;while(! q.isEmpty()){int size = q.size();
count += size;for(int i =0; i < size; i++){int id = q.poll();
indegree[id]--;// if count == n, add the id of node into the resulting listif(count == n) list.add(id);for(int adjId : map.get(id)){// if indegree of a node equals to 0, it means this node has already been added into the result listif(indegree[adjId]!=0){
indegree[adjId]--;if(indegree[adjId]==1) q.offer(adjId);}}}}return list;}}