Count pairs of nodes having minimum distance between them equal to the difference of their distances from root | Stores the count of pairs ; Store the adjacency list of the connecting vertex ; Function for theto perform DFS traversal of the given tree ; Traverse the adjacency list of the current node u ; If the current node is the parent node ; Add number of ancestors , which is same as depth of the node ; Function for DFS traversal of the given tree ; Print the result ; Function to find the count of pairs such that the minimum distance between them is equal to the difference between distance of the nodes from root node ; Add edges to adj [ ] ; Driver Code
var ans = 0 ; var adj = Array . from ( Array ( 100001 ) , ( ) => Array ( ) ) ; function dfsUtil ( u , par , depth ) { adj [ u ] . forEach ( it => { if ( it != par ) { dfsUtil ( it , u , depth + 1 ) ; } } ) ; ans += depth ; } function dfs ( u , par , depth ) { dfsUtil ( u , par , depth ) ; document . write ( ans + " " ) ; } function countPairs ( edges ) { for ( var i = 0 ; i < edges . length ; i ++ ) { var u = edges [ i ] [ 0 ] ; var v = edges [ i ] [ 1 ] ; adj [ u ] . push ( v ) ; adj [ v ] . push ( u ) ; } dfs ( 1 , 1 , 1 ) ; } var edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 4 ] ] ; countPairs ( edges ) ;