Find centroid of the current tree using the algorithm from the previous problem.
DFS from to get distances to all nodes. Count pairs with distance sum using a frequency map.
For each child subtree, DFS again and subtract pairs where both nodes are in that subtree.
Remove and recursively process each component.
Time: because each node is processed times and each processing is or .
Space complexity is for the data structures used.