Graph Theory37 sections · 1633 units
Open in Course

Subtree Size

(Counting descendants)

For each node vv, let size[v] be the size of its subtree, including vv itself. You compute this with a single DFS using the formula size[v] = 1 + Σ_u in children[v] size[u]. For a leaf, size[v] = 1 since it has no children. For an internal node, you add 11 for the node itself plus the sizes of all child subtrees.

Subtree sizes determine which edges are heavy. Nodes with large subtrees get heavy edges. This computation takes O(n)O(n) time, visiting each node once.

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