Find triplet such that number of nodes connecting these triplets is maximum | JavaScript implementation of the approach ; To store the required nodes ; Parent array to retrace the nodes ; Visited array to prevent DFS in direction on Diameter path ; DFS function to find the startnode ; DFS function to find the endnode of diameter and maintain the parent array ; DFS function to find the end node of the Longest Branch to Diameter ; Function to find the required nodes ; To find start node of diameter ; To find end node of diameter ; x is the end node of diameter ; Mark all the nodes on diameter using back tracking ; Find the end node of longest branch to diameter ; Driver code
let MAX = 100005 ; let adjacent = [ ] ; let visited = new Array ( MAX ) ; let startnode , endnode , thirdnode ; let maxi = - 1 , N ; let parent = new Array ( MAX ) ; let vis = new Array ( MAX ) ; function dfs ( u , count ) { visited [ u ] = true ; let temp = 0 ; for ( let i = 0 ; i < adjacent [ u ] . length ; i ++ ) { if ( ! visited [ adjacent [ u ] [ i ] ] ) { temp ++ ; dfs ( adjacent [ u ] [ i ] , count + 1 ) ; } } if ( temp == 0 ) { if ( maxi < count ) { maxi = count ; startnode = u ; } } } function dfs1 ( u , count ) { visited [ u ] = true ; let temp = 0 ; for ( let i = 0 ; i < adjacent [ u ] . length ; i ++ ) { if ( ! visited [ adjacent [ u ] [ i ] ] ) { temp ++ ; parent [ adjacent [ u ] [ i ] ] = u ; dfs1 ( adjacent [ u ] [ i ] , count + 1 ) ; } } if ( temp == 0 ) { if ( maxi < count ) { maxi = count ; endnode = u ; } } } function dfs2 ( u , count ) { visited [ u ] = true ; let temp = 0 ; for ( let i = 0 ; i < adjacent [ u ] . length ; i ++ ) { if ( ! visited [ adjacent [ u ] [ i ] ] && ! vis [ adjacent [ u ] [ i ] ] ) { temp ++ ; dfs2 ( adjacent [ u ] [ i ] , count + 1 ) ; } } if ( temp == 0 ) { if ( maxi < count ) { maxi = count ; thirdnode = u ; } } } function findNodes ( ) { dfs ( 1 , 0 ) ; for ( let i = 0 ; i <= N ; i ++ ) visited [ i ] = false ; maxi = - 1 ; dfs1 ( startnode , 0 ) ; for ( let i = 0 ; i <= N ; i ++ ) visited [ i ] = false ; let x = endnode ; vis [ startnode ] = true ; while ( x != startnode ) { vis [ x ] = true ; x = parent [ x ] ; } maxi = - 1 ; for ( let i = 1 ; i <= N ; i ++ ) { if ( vis [ i ] ) dfs2 ( i , 0 ) ; } } for ( let i = 0 ; i < MAX ; i ++ ) adjacent . push ( [ ] ) ; N = 4 ; adjacent [ 1 ] . push ( 2 ) ; adjacent [ 2 ] . push ( 1 ) ; adjacent [ 1 ] . push ( 3 ) ; adjacent [ 3 ] . push ( 1 ) ; adjacent [ 1 ] . push ( 4 ) ; adjacent [ 4 ] . push ( 1 ) ; findNodes ( ) ; document . write ( " " + startnode + " " + endnode + " " + thirdnode + " " ) ;