Graph Theory37 sections · 1633 units
Open in Course

Algorithm - Count Paths Through Centroid

(The recursive structure)

1.1. Find centroid cc of the current tree using the algorithm from the previous problem.

2.2. DFS from cc to get distances to all nodes. Count pairs with distance sum kk using a frequency map.

3.3. For each child subtree, DFS again and subtract pairs where both nodes are in that subtree.

4.4. Remove cc and recursively process each component.

Time: O(nlogn)O(n \log n) because each node is processed O(logn)O(\log n) times and each processing is O(1)O(1) or O(logn)O(\log n).

Space complexity is O(n)O(n) for the data structures used.