DFS function to find the endnode of diameter and maintain the parent array
static void dfs1 ( int u , int count ) { visited [ u ] = true ; int temp = 0 ; for ( int i = 0 ; i < adjacent . get ( u ) . size ( ) ; i ++ ) { if ( ! visited [ adjacent . get ( u ) . get ( i ) ] ) { temp ++ ; parent [ adjacent . get ( u ) . get ( i ) ] = u ; dfs1 ( adjacent . get ( u ) . get ( i ) , count + 1 ) ; } } if ( temp == 0 ) { if ( maxi < count ) { maxi = count ; endnode = u ; } } }