Graph Theory37 sections · 1633 units
Open in Course

Finding the Centroid

(Walk toward heavy subtrees)

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 that takes O(n)O(n) time.

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). 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.