Data Structures19 sections · 729 units
Open in Course

Finding the Centroid

The algorithm

A centroid is a node cc where every subtree has at most n/2n/2 nodes after removing cc. To find it:

1.1. Pick any root and compute subtree sizes

2.2. Start at the root

3.3. If any child's subtree has >n/2> n/2 nodes, move to that child

4.4. Otherwise, current node is the centroid

Why does this work? At each step, you move toward larger subtrees. When you stop, no subtree exceeds n/2n/2 nodes, so you're at a centroid. Time: O(n)O(n) for computing sizes and finding centroid.