Filling edge data structure
@ SuppressWarnings ( " unchecked " ) ArrayList < Integer > [ ] edge = new ArrayList [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { edge [ i ] = new ArrayList < > ( ) ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { edge [ edges [ i ] [ 0 ] ] . add ( edges [ i ] [ 1 ] ) ; edge [ edges [ i ] [ 1 ] ] . add ( edges [ i ] [ 0 ] ) ; }