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 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
ans = 0 NEW_LINE adj = [ [ ] for i in range ( 10 ** 5 + 1 ) ] NEW_LINE def dfsUtil ( u , par , depth ) : NEW_LINE INDENT global adj , ans NEW_LINE for it in adj [ u ] : NEW_LINE INDENT if ( it != par ) : NEW_LINE INDENT dfsUtil ( it , u , depth + 1 ) NEW_LINE DEDENT DEDENT ans += depth NEW_LINE DEDENT def dfs ( u , par , depth ) : NEW_LINE INDENT global ans NEW_LINE dfsUtil ( u , par , depth ) NEW_LINE print ( ans ) NEW_LINE DEDENT def countPairs ( edges ) : NEW_LINE INDENT global adj NEW_LINE for i in range ( len ( edges ) ) : NEW_LINE INDENT u = edges [ i ] [ 0 ] NEW_LINE v = edges [ i ] [ 1 ] NEW_LINE adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT dfs ( 1 , 1 , 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 4 ] ] NEW_LINE countPairs ( edges ) NEW_LINE DEDENT