Graph Theory37 sections · 1633 units
Open in Course

Core idea 1 - Subtree Sizes

(Compute sizes with DFS)

To check if a node is a centroid, you compute the size of each component that would remain after removing it. These are subtree sizes in a rooted tree, plus the parent direction. Run DFS from any root to compute size[v] for each node. This takes O(n)O(n) time with a simple recursive traversal. Store the sizes in an array.

Now you can check any node in O(degree)O(\text{degree}) time by looking at its children's sizes and computing the parent component size as n - size[v].