Graph Theory37 sections · 1633 units
Open in Course

Core idea 2 - Combining Subtree Paths

Count distances from centroid

From centroid cc, run DFS to find the distance from cc to every node in its subtree. Store these distances in an array or map. A path of length kk through cc consists of two parts: distance d1d_1 from cc to node uu and distance d2d_2 from cc to node vv, where d1+d2=kd_1 + d_2 = k. You are looking for pairs that sum to kk.

For each distance dd, count how many nodes are at distance kdk - d. Sum these counts. Use a frequency map for O(1)O(1) lookup.