##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
You've done DP on arrays. Now states live at tree nodes. Solve Binary Tree Max Path Sum and learn how to aggregate child results at each vertex.
Aggregate from subtrees
Diameters, paths, and matchings
No cycles, natural recursion
LC 124 - any path, max sum
The bend point insight
Return vs update: what's the difference?
max(0, child) avoids negatives
Null = 0, leaf = its value
Global update inside DFS
O(n) time, O(h) space
All negative? Skewed tree?
Return one direction, update both
CSES - distance sum per node
Reroot in O(1), not O(n)
Subtree size and subtree sum
Moving root flips distances
First DFS from arbitrary root
Two DFS passes, O(n) total
O(n) beats naive O(n²)
Star graph vs path graph
Reroot when answer depends on root
CF 161D - pairs at distance k
Combine depths across subtrees
cnt[d] = nodes at depth d
Match d and k-d across children
Small-to-large for O(n log n)
Depth counting, not pair enumeration
LC 543 - longest path in edges
leftDepth + rightDepth through node
O(n) single pass
CF 1187E - maximize paint score
Sum of subtree sizes
score[v] = score[u] + n - 2*size[v]
Maximum matching in tree
dp[v][matched] or dp[v][unmatched]
Greedy from leaves up
LC 968 - minimum cameras
Three states: uncovered, covered, has camera
Which subtree pattern is this?
Single node, empty tree
Post-order for bottom-up
LC 2246
Solution approach
From path sum to rerooting