Why it matters

Tree DP handles many tree problems elegantly.

Advertisement

The architecture

Post-order: children computed before parent.

Combine children states.

Tree DP patternPost-orderchildren firstCombinechild statesResult per nodeor rootTree diameter: farthest two leaves via tree DP
Tree DP.
Advertisement

How it works end to end

Diameter: track deepest + second deepest from each node.

Matching: match or not match each node.

Rerooting DP: change root; recompute in O(1) per node.