Graph Theory37 sections · 1633 units
Open in Course

Complexity Analysis

(Why it's O(n log n))

Finding a centroid takes O(n)O(n) time for a tree with nn nodes. The recursion has O(logn)O(\log n) depth because each level halves component sizes. Each node appears in O(logn)O(\log n) recursive calls. Processing paths through a centroid takes O(n)O(n) time for that subtree.

Since each node is processed O(logn)O(\log n) times across all levels, total time is O(nlogn)O(n \log n). Overall: O(nlogn)O(n \log n) for building the decomposition and solving path problems. Space is O(n)O(n) for the tree and auxiliary arrays.

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