From centroid , run DFS to find the distance from to every node in its subtree. Store these distances in an array or map. A path of length through consists of two parts: distance from to node and distance from to node , where . You are looking for pairs that sum to .
For each distance , count how many nodes are at distance . Sum these counts. Use a frequency map for lookup.