Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U | To store the time ; Function to perform DFS to store times , distance and parent of each node ; Update the distance of node u ; Update parent of node u ; Increment time timeT ; Discovery time of node u ; Traverse the adjacency list of current node and recursively call DFS for each vertex ; If current node Adj [ u , i ] is unvisited ; Update the finishing time ; Function to add edges between nodes u and v ; Function to find the node U such that path from root to U contains nodes in V [ ] ; Initialise vis , dis , parent , preTime , and postTime ; Store Adjacency List ; Create adjacency List ; Perform DFS Traversal ; Stores the distance of deepest vertex ' u ' ; Update the deepest node by traversing the qu [ ] ; Find deepest vertex ; Replace each vertex with it 's  corresponding parent except  the root vertex ; Checks if the ancestor with respect to deepest vertex u ; Update ans ; Print the result ; Total vertices ; Given set of vertices ; Given edges ; Function call
let timeT = 0 ; function dfs ( u , p , dis , vis , distance , parent , preTime , postTime , Adj ) { distance [ u ] = dis ; parent [ u ] = p ; vis [ u ] = 1 ; timeT ++ ; preTime [ u ] = timeT ; for ( let i = 0 ; i < Adj [ u ] . length ; i ++ ) { if ( vis [ Adj [ u ] [ i ] ] == 0 ) { dfs ( Adj [ u ] [ i ] , u , dis + 1 , vis , distance , parent , preTime , postTime , Adj ) ; } } timeT ++ ; postTime [ u ] = timeT ; } function addEdge ( Adj , u , v ) { Adj [ u ] . push ( v ) ; Adj [ v ] . push ( u ) ; } function findNodeU ( N , V , Vertices , Edges ) { let vis = new Array ( N + 1 ) ; vis . fill ( 0 ) ; let distance = new Array ( N + 1 ) ; distance . fill ( 0 ) ; let parent = new Array ( N + 1 ) ; parent . fill ( 0 ) ; let preTime = new Array ( N + 1 ) ; preTime . fill ( 0 ) ; let postTime = new Array ( N + 1 ) ; postTime . fill ( 0 ) ; let Adj = [ ] ; for ( let i = 0 ; i < N + 1 ; i ++ ) Adj . push ( [ ] ) ; let u = 0 , v ; for ( let i = 0 ; i < N - 1 ; i ++ ) { addEdge ( Adj , Edges [ i ] [ 0 ] , Edges [ i ] [ 1 ] ) ; } dfs ( 1 , 0 , 0 , vis , distance , parent , preTime , postTime , Adj ) ; let maximumDistance = 0 ; maximumDistance = 0 ; for ( let k = 0 ; k < V ; k ++ ) { if ( maximumDistance < distance [ Vertices [ k ] ] ) { maximumDistance = distance [ Vertices [ k ] ] ; u = Vertices [ k ] ; } if ( parent [ Vertices [ k ] ] != 0 ) { Vertices [ k ] = parent [ Vertices [ k ] ] ; } } let ans = true ; let flag ; for ( let k = 0 ; k < V ; k ++ ) { if ( preTime [ Vertices [ k ] ] <= preTime [ u ] && postTime [ Vertices [ k ] ] >= postTime [ u ] ) flag = true ; else flag = false ; ans = ans & flag ; } if ( ans ) document . write ( u ) ; else document . write ( " " ) ; } let N = 10 ; let V = 5 ; let Vertices = [ 4 , 3 , 8 , 9 , 10 ] ; let Edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] , [ 2 , 5 ] , [ 2 , 6 ] , [ 3 , 7 ] , [ 7 , 8 ] , [ 7 , 9 ] , [ 9 , 10 ] ] ; findNodeU ( N , V , Vertices , Edges ) ;