AdvancedAbout 35 min

    DP on Trees

    Read the full article on Substack

    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.

    -10920157

    Solve children before parents (post-order). Each node reports its best downward path.

    1/7

    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

    Sequence

    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.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Quiz

    20 questions
    Question 1 of 20
    Score: 0

    In "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.

    Keep going