If both endpoints are in the same subtree of , the path does not pass through . You will count it later in the recursion when you process that subtree. To avoid double-counting, subtract paths where both endpoints are in the same child subtree.
Process each child's subtree separately: get its distances, count pairs, and subtract from the total. This is the subtract step in the inclusion-exclusion principle. Add all pairs, subtract same-subtree pairs. What remains is paths through .