File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ class  Solution  {
2+  public  List <Integer > findMinHeightTrees (int  n , int [][] edges ) {
3+  if  (n  == 1 ) {
4+  return  Arrays .asList (0 );
5+  }
6+ 
7+  List <Set <Integer >> adjList  = new  ArrayList <>();
8+  List <Integer > leaves  = new  ArrayList <>();
9+ 
10+  for  (int  i  = 0 ; i  < n ; i ++) {
11+  adjList .add (new  HashSet <>());
12+  }
13+ 
14+  for  (int [] edge  : edges ) {
15+  adjList .get (edge [0 ]).add (edge [1 ]);
16+  adjList .get (edge [1 ]).add (edge [0 ]);
17+  }
18+ 
19+  for  (int  i  = 0 ; i  < n ; i ++) {
20+  if  (adjList .get (i ).size () == 1 ) {
21+  leaves .add (i );
22+  }
23+  }
24+ 
25+  while  (n  > 2 ) {
26+  n  -= leaves .size ();
27+  List <Integer > newLeaves  = new  ArrayList <>();
28+ 
29+  for  (int  currLeaf  : leaves ) {
30+  int  adjLeaf  = adjList .get (currLeaf ).iterator ().next ();
31+  adjList .get (adjLeaf ).remove (currLeaf );
32+  if  (adjList .get (adjLeaf ).size () == 1 ) {
33+  newLeaves .add (adjLeaf );
34+  }
35+  }
36+ 
37+  leaves  = newLeaves ;
38+  }
39+ 
40+  return  leaves ;
41+  }
42+ }
                         You can’t perform that action at this time. 
           
                  
0 commit comments