Graph Theory37 sections · 1633 units
Open in Course

Core idea 3 - Subtract Same-Subtree Paths

Avoid counting paths within...

If both endpoints are in the same subtree of cc, the path does not pass through cc. 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 cc.