DP on Trees
6 min read.
Tree Dynamic Programming applies DP bottom-up through a rooted tree, processing children before parents in a post-order DFS so each subtree is solved exactly once. Because trees are acyclic, there are no overlapping subproblems across branches — each child's result is computed once and aggregated upward to its parent. Classic problems include finding the tree diameter, the maximum path sum (where a path can branch through a node), and the maximum weight independent set (where chosen nodes cannot be adjacent). This visualization animates the Maximum Path Sum algorithm on a five-node binary tree, showing how each node separately tracks the best downward path to return to its parent and the best full path through itself that updates the global answer.
Think of it this way: Imagine a company org chart. To calculate the total bonus pool, each manager sums their team's bonuses and passes the total up. DP on trees computes values bottom-up from leaves to root.
Solve children before parents (post-order). Each node reports its best downward path.
Check your understanding
Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.
Maximum independent set on a tree
Order the steps of the take/skip tree DP.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
- 1Drop a step here
- 2Drop a step here
- 3Drop a step here
- 4Drop a step here
- 5Drop a step here
Quiz
20 questionsIn "Binary Tree Maximum Path Sum", why must we return a different value than we update?
Done with this lesson?
Sign in free to keep your progress, streak and quiz scores.