01Answers bubble up from the leaves
On a rooted tree, the natural subproblem is “the answer for the subtree of v”. Subtrees of different children do not overlap, and the subtree of v is just v plus its children’s subtrees. So:
- the state lives on vertices:
dp[v], sometimes with a small extra flag; - the order is post-order DFS: finish every child before its parent;
- each vertex combines its children’s values, so every edge is looked at once: O(n) in total.
The simplest example is subtree size: size[v] = 1 + Σ size[child]. Leaves have size 1, and the root gets n. It looks trivial, but sizes are used everywhere: counting pairs through an edge, finding a centroid, heavy-light decomposition.
Recursion is the easiest way to write it; for very deep trees (a path of 10⁵ vertices) use an explicit stack to avoid stack overflow.