Graph Theory37 sections · 1633 units
Open in Course

Algorithm - Find Centroid

(Two-phase approach)

1.1. DFS from any root to compute subtree sizes for all nodes.

Store them in an array for quick lookup. This is a standard tree traversal.

2.2. Start at the root.

While the current node vv has a child uu with size[u] > n/2, move to uu. When no such child exists, return vv as the centroid. The first phase takes O(n)O(n) time for the tree traversal. The second phase visits at most nn nodes in the worst case (imagine a line graph where you walk the entire length), so total time is O(n)O(n).

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