Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 25

Tree DP: Canonical Problems

This lesson is built with resources from youtube.com, algo.monster and 1 more site.

Hello! Welcome to the final lesson in our module on Core Dynamic Programming Patterns.

In our previous lessons, we've built a strong foundation, moving from 1D and 2D DP to more advanced patterns like interval and bitmask DP. You've seen how the key to DP is defining a state that captures the necessary information to solve a larger problem.

Today, we shift our focus from linear sequences and subsets to hierarchical structures. This lesson covers Dynamic Programming on Trees. Our learning outcome is to solve canonical tree DP problems, using "House Robber III" and "Diameter of a Binary Tree" as our primary examples.

The fundamental pattern you'll learn involves a post-order traversal (a form of DFS), where the solution for a parent node is computed using the results from its children. Your experience with recursion and tree traversals will be a great asset here; the main challenge lies in defining what information needs to be passed up the tree from child to parent.

The General Tree DP Pattern

Dynamic programming on trees typically follows a consistent structure:

  1. Traversal: A recursive Depth-First Search (DFS) is used to traverse the tree. The computation for a node happens after the recursive calls for its children have returned. This is known as a post-order traversal.
  2. State Definition: The subproblem is defined for the subtree rooted at a given node u.
  3. Information Flow: The recursive function dfs(u) calculates the DP value(s) for the subtree at u and returns this information to its parent.

The most critical design decision is determining the return value of the dfs function. What information must a child pass to its parent for the parent to solve its own subproblem? As we'll see, this can range from a single integer to a tuple or struct containing multiple values.

Dynamic Programming on Trees Example
This image illustrates the bottom-up nature of Tree DP. The `dp` value for each node is calculated after its children's values are known, propagating the computation from the leaves up to the root.


Problem 1: House Robber III

This problem is a variation of the "House Robber" series, but the houses are arranged in a binary tree.

The rule: You cannot rob two directly-linked houses (a parent and its child).
The goal: Maximize the total amount of money you can rob.

This constraint forces a decision at every node: do we rob this house or not?

  • If we rob the current node u, we gain u.val, but we are forbidden from robbing its left and right children. We must therefore take the maximum profit from the grandchildren's subtrees.
  • If we don't rob the current node u, we get 0 from it, but we are free to get the maximum possible profit from both the left and right children's subtrees.

This reveals a dependency: the decision at node u requires knowing the optimal outcomes for its children under different constraints. This is the perfect setup for DP.

The crucial insight is that for any node u, we need to compute two distinct values:

  1. The maximum amount we can rob from the subtree at u if we rob u itself.
  2. The maximum amount we can rob from the subtree at u if we do not rob u.

Our DFS function will therefore return a pair of values for each node.

House Robber III - Tree - Leetcode 337

The video 'House Robber III' from the NeetCode channel provides an excellent explanation of this dual-state approach. Let's watch the key segment where this logic is introduced.

Please watch from the beginning up to 05:19. 00:14 - 01:41: Understand the problem statement and the core constraint. 01:48 - 05:19: Pay close attention to how the problem is broken down into two cases ('with root' and 'without root') and how this leads to a modified DFS that returns a pair of values. This is the heart of the DP solution.

Recurrence Relation

Based on the video, let's formalize the recurrence. Our function dfs(node) will return a pair [rob_this_node, skip_this_node].

  1. Base Case: If node is nil, we can't rob anything. We return [0, 0].

  2. Recursive Step: For a non-nil node:

    • First, recursively call on the children:
      left_rob, left_skip = dfs(node.left)
      right_rob, right_skip = dfs(node.right)
    • Calculate the two values for the current node:
      • rob_this_node = node.val + left_skip + right_skip
        (If we rob the current node, we must skip its direct children).
      • skip_this_node = max(left_rob, left_skip) + max(right_rob, right_skip)
        (If we skip the current node, we are free to take the best possible result from the left and right subtrees independently).
    • Return [rob_this_node, skip_this_node].
  3. Final Answer: The final result for the entire tree is the maximum of the two values returned for the root node: max(dfs(root)).

This approach ensures we visit each node only once, leading to an time complexity, where is the number of nodes. The space complexity is for the recursion stack, where is the height of the tree.

House Robber III - In-Depth Explanation

For a detailed textual breakdown and implementation examples, the 'House Robber III - In-Depth Explanation' from AlgoMonster is a great resource. It reinforces the intuition and provides a clear example walkthrough.

Please read the sections 'Intuition', 'Solution Approach', and 'Example Walkthrough'. This will solidify the logic we just discussed and show how the values are propagated up the tree.



Problem 2: Diameter of a Binary Tree

The diameter of a binary tree is the length of the longest path between any two nodes. This path may or may not pass through the root.

Diameter of a Binary Tree: Paths Through and Not Through Root
This image shows two cases for the diameter. On the left, the longest path is contained entirely within a subtree. On the right, the longest path passes through the root of the tree.

For any given node u, the longest path can be in one of three places:

  1. Entirely within the left subtree of u.
  2. Entirely within the right subtree of u.
  3. Passing through u itself.

The length of a path passing through u is the (height of left subtree) + (height of right subtree).

A naive approach would be to iterate through every node, calculate the heights of its left and right subtrees, sum them up, and keep track of the maximum sum found. However, calculating height for each node separately would lead to an solution in the worst case (for a skewed tree), as height calculation is .

We can do better with a single DFS traversal. The key is to realize what information we need to compute and what we need to pass up.

At a node u:

  • To calculate the diameter passing through u: We need the heights of its left and right children. Let's call them left_height and right_height. The diameter through u would be left_height + right_height. We can use this to update a global diameter variable.
  • To help u's parent: The parent of u will need the height of the subtree rooted at u to calculate its own diameter. The height of the subtree at u is 1 + max(left_height, right_height).

So, our DFS function can do two jobs at once:

  1. Update a global variable for the diameter.
  2. Return its own height to its parent.

L16. Diameter of Binary Tree | C++ | Java

The video 'L16. Diameter of Binary Tree' from the 'take U forward' channel explains this optimization beautifully.

Please watch from 02:01 to 12:16. 02:01 - 06:41: Understand the O(N^2) naive approach and why it's inefficient. 06:41 - 12:16: Focus on the optimized O(N) solution. Notice how the function calculates the height to return to its parent, but along the way, it uses the children's heights to update a global maximum diameter. This is a classic Tree DP pattern.

Go Implementation Note

In the video, the author uses a reference variable (in C++) to update the diameter. In Go, you can achieve the same effect by passing a pointer to the diameter variable into your recursive helper function.

func diameterOfBinaryTree(root *TreeNode) int {
    diameter := 0
    // Pass the address of 'diameter' to the helper function
    calculateHeight(root, &diameter)
    return diameter
}

// calculateHeight returns the height of the subtree at 'node'
// and updates the diameter pointer.
func calculateHeight(node *TreeNode, diameter *int) int {
    if node == nil {
        return 0
    }

    leftHeight := calculateHeight(node.left, diameter)
    rightHeight := calculateHeight(node.right, diameter)

    // Update the diameter with the path going through the current node
    *diameter = max(*diameter, leftHeight + rightHeight)

    // Return the height of the current subtree to the parent
    return 1 + max(leftHeight, rightHeight)
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}


Staff+ Depth: Generalizations and Optimizations

For a Staff-level interview, demonstrating an understanding of how these patterns generalize is crucial.

  1. State Representation is Key: The two problems we studied showcase the two most common return patterns in Tree DP:

    • Returning a single value needed by the parent (e.g., height in Diameter).
    • Returning a tuple/struct of values representing different choices at the current node (e.g., [rob, skip] in House Robber III).
      When faced with a new tree problem, always start by asking: "What are the choices at a node, and what information from its children do I need to make the best choice?"
  2. Advanced State Compression: In competitive programming, there are even more advanced optimizations. For instance, in a problem like finding the maximum matching in a tree, the DP state might be (dt[v], dn[v]) representing the size of the matching with v and without v, respectively. It can be proven that dt[v] and dn[v] differ by at most 1. This allows the two states to be compressed into a single integer and a boolean flag, saving memory. The Algonotes article "Dynamic programming on trees with minimal memory" (LINK) explores these extreme optimizations, which, while not typically required to code in an interview, are excellent to be aware of as they show a deep command of efficiency.



Conclusion

This lesson wraps up our module on core DP patterns by extending them to tree structures.

Key Takeaways:

  • Pattern: Tree DP problems are almost always solved with a post-order traversal (recursive DFS).
  • Information Flow: The solution for a node u is built from the solutions for its children. The main design task is defining what values the recursive function should return.
  • Two Models:
    • House Robber III: The recursive function returns multiple values representing the optimal results for different choices at the current node (e.g., [rob_here, skip_here]).
    • Diameter of a Tree: The recursive function returns a single value needed by its parent (e.g., height), while simultaneously using information from its children to update a global answer (e.g., diameter).

Preview of the Next Lesson:
You have now mastered a significant number of specific DP patterns. The next module, "Hard-Level Coding Problem Strategies," moves to a higher level of abstraction. In our next lesson, we will focus on the meta-skill of decomposing complex problems into subproblems. This is about the art of problem-solving itself—how to look at a difficult, unfamiliar problem statement and systematically dissect it to find an underlying structure that you can apply patterns like DP or graph algorithms to. This is a vital skill for tackling the open-ended challenges common in Staff+ interviews.