Skip to lesson

Tree dynamic programming

Tree dynamic programming solves optimization and counting problems on hierarchical tree topologies. Because trees have no cycles, post-order traversal provides the exact topological order needed.

Brute Force Tree Recursion vs Post-Order DFS

House Robber III places houses on a binary tree: you cannot rob directly connected parent and child houses. Without dynamic programming, plain recursion tries both choices at every node (shown after the code).

Java
int rob(TreeNode u) {    if (u == null) return 0;    int take = u.val;                          // rob u: jump to grandchildren    if (u.left != null) take += rob(u.left.left) + rob(u.left.right);    if (u.right != null) take += rob(u.right.left) + rob(u.right.right);    int skip = rob(u.left) + rob(u.right);     // skip u: children are free    return Math.max(take, skip);               // grandchildren are solved again and again}

With plain top-down recursion, from node u you either rob u (which skips u's children and calls u's grandchildren) or skip u (which calls u's children). When child calls make their own recursive grandchild calls, subtrees overlap heavily, creating an exponential O(2^n) recursion tree on deep trees!

Post-order depth-first search solves this cleanly in a single pass: visit the left child, visit the right child, and then compute the parent. Because children are evaluated before the parent, every node is visited exactly once in linear O(n) time.

Multi-State Decisions: Returning Tuples

In House Robber III, returning a single integer from each node is not enough because the parent must know whether the child was robbed or skipped.

Instead, each recursive call returns a 2-element array: int[] res = {robScore, notRobScore}.

Example 1 · House Robber on a tree by plain recursion, brute force: exponential time, O(h) space

RobberBruteDemo.javaJava
public class RobberBruteDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int val) { this.val = val; }    }
    static int rob(TreeNode node) {        if (node == null) return 0;        int take = node.val;                             // rob this house: skip its children        if (node.left != null) take += rob(node.left.left) + rob(node.left.right);        if (node.right != null) take += rob(node.right.left) + rob(node.right.right);        int skip = rob(node.left) + rob(node.right);     // skip this house        return Math.max(take, skip);                     // grandchildren are solved twice    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(3);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.right = new TreeNode(3);        root.right.right = new TreeNode(1);        System.out.println("Max loot from tree: " + rob(root));    }}
Output
Max loot from tree: 7

What this code does

  • Robbing a node adds its value plus the best of its grandchildren; skipping it adds the best of its children.
  • A grandchild is solved once as a grandchild and again as a child, so the repeated work doubles with depth.
  • It prints 7, the same as the pair version.

Example 2 · House Robber on a tree with a memo map, better: O(n) time, O(n) space

RobberMemoDemo.javaJava
import java.util.HashMap;import java.util.Map;
public class RobberMemoDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int val) { this.val = val; }    }
    static Map<TreeNode, Integer> memo = new HashMap<>();
    static int rob(TreeNode node) {        if (node == null) return 0;        if (memo.containsKey(node)) return memo.get(node);   // answer already known        int take = node.val;        if (node.left != null) take += rob(node.left.left) + rob(node.left.right);        if (node.right != null) take += rob(node.right.left) + rob(node.right.right);        int skip = rob(node.left) + rob(node.right);        int result = Math.max(take, skip);        memo.put(node, result);                          // remember it for next time        return result;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(3);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.right = new TreeNode(3);        root.right.right = new TreeNode(1);        System.out.println("Max loot from tree: " + rob(root));    }}
Output
Max loot from tree: 7

What this code does

  • memo stores the best loot for each node after it is computed.
  • A later call for the same node returns the stored value immediately.
  • It is linear now, but needs a map. The pair version gets O(n) with no map at all.

Example 3 · House Robber on a tree with pairs, optimal: O(n) time, O(h) space

HouseRobberTreeDemo.javaJava
class TreeNode {    int val;    TreeNode left, right;    TreeNode(int val) { this.val = val; }}
public class HouseRobberTreeDemo {    public static int rob(TreeNode root) {        int[] res = dfs(root);        return Math.max(res[0], res[1]);    }
    private static int[] dfs(TreeNode node) {        if (node == null) return new int[]{0, 0};
        int[] left = dfs(node.left);        int[] right = dfs(node.right);
        // res[0] = rob current, res[1] = do not rob current        int rob = node.val + left[1] + right[1];        int notRob = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        return new int[]{rob, notRob};    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(3);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.right = new TreeNode(3);        root.right.right = new TreeNode(1);
        System.out.println("Max loot from tree: " + rob(root));    }}
Output
Max loot from tree: 7

What this code does

  • Returns a 2-tuple [rob, notRob] from each node representing optimal loot under both states.
  • Robbing the parent forces both children to use their notRob scores.
  • Runs in linear O(n) time using call-stack space proportional to tree height.
  • Why faster: each node returns a pair (rob, skip), so no node re-solves its grandchildren and no map is needed.

If the current node is robbed, both children MUST be skipped: rob = node.val + left[1] + right[1]. If the current node is skipped, each child can independently be robbed or skipped: notRob = Math.max(left[0], left[1]) + Math.max(right[0], right[1]). Returning state tuples solves multi-choice tree constraints without extra tables.

Global Optimization vs Branch Return Value

Problems like Binary Tree Maximum Path Sum distinguish between the value returned to the parent and the global answer updated along the way.

Example 4 · Binary tree maximum path sum: O(n) time, O(h) space

MaxPathSumDemo.javaJava
class TreeNode {    int val;    TreeNode left, right;    TreeNode(int val) { this.val = val; }}
public class MaxPathSumDemo {    private static int maxSum;
    public static int maxPathSum(TreeNode root) {        maxSum = Integer.MIN_VALUE;        maxGain(root);        return maxSum;    }
    private static int maxGain(TreeNode node) {        if (node == null) return 0;
        int leftGain = Math.max(0, maxGain(node.left));        int rightGain = Math.max(0, maxGain(node.right));
        // Path passing through this node as highest turning point        int priceNewPath = node.val + leftGain + rightGain;        if (priceNewPath > maxSum) {            maxSum = priceNewPath;        }
        // Return max branch extending upward        return node.val + Math.max(leftGain, rightGain);    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(-10);        root.left = new TreeNode(9);        root.right = new TreeNode(20);        root.right.left = new TreeNode(15);        root.right.right = new TreeNode(7);
        System.out.println("Max path sum in tree: " + maxPathSum(root));    }}
Output
Max path sum in tree: 42

What this code does

  • Ignores negative child contributions by clamping child gains with Math.max(0, gain).
  • Updates global maximum using both left and right branches meeting at the current node.
  • Returns only the single best downward branch to the caller to maintain path linearity.

Example 5 · Diameter of a binary tree with repeated heights, brute force: O(n²) time, O(h) space

DiameterBruteDemo.javaJava
public class DiameterBruteDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int val) { this.val = val; }    }
    static int height(TreeNode node) {        if (node == null) return 0;        return 1 + Math.max(height(node.left), height(node.right));    }
    static int diameter(TreeNode node) {        if (node == null) return 0;        int through = height(node.left) + height(node.right);   // path bending at this node        int inLeft = diameter(node.left);        int inRight = diameter(node.right);        return Math.max(through, Math.max(inLeft, inRight));    // height() re-walks each subtree    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.left = new TreeNode(4);        root.left.right = new TreeNode(5);        System.out.println("Diameter of binary tree: " + diameter(root));    }}
Output
Diameter of binary tree: 3

What this code does

  • At each node the longest path bending there is height(left) + height(right).
  • height() walks the whole subtree every time, so nodes near the top are visited many times.
  • It prints 3, the same as the one-pass version, but a skewed tree makes it quadratic.

Example 6 · Diameter of a binary tree in one pass, optimal: O(n) time, O(h) space

TreeDiameterDemo.javaJava
class TreeNode {    int val;    TreeNode left, right;    TreeNode(int val) { this.val = val; }}
public class TreeDiameterDemo {    private static int maxDiameter;
    public static int diameterOfBinaryTree(TreeNode root) {        maxDiameter = 0;        depth(root);        return maxDiameter;    }
    private static int depth(TreeNode node) {        if (node == null) return 0;        int left = depth(node.left);        int right = depth(node.right);        maxDiameter = Math.max(maxDiameter, left + right);        return 1 + Math.max(left, right);    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.left = new TreeNode(4);        root.left.right = new TreeNode(5);
        System.out.println("Diameter of binary tree: " + diameterOfBinaryTree(root));    }}
Output
Diameter of binary tree: 3

What this code does

  • Recursively computes subtree depths while maintaining the maximum diameter encountered.
  • Diameter at any node equals left depth plus right depth in edges.
  • Runs in single-pass O(n) time.
  • Why faster: one post-order pass returns each height and updates the diameter at the same time, so no subtree is walked twice.

A valid path can bend at node u, connecting u's left branch, node u itself, and u's right branch. However, node u cannot extend both downward branches upward to its parent without splitting the path! Therefore, the recursive helper returns node.val + Math.max(0, Math.max(leftGain, rightGain)) to the parent, while updating globalMax = Math.max(globalMax, node.val + leftGain + rightGain).

The Tree Rerooting Technique

The rerooting technique computes an answer with every node as the root (such as the sum of distances from every vertex) without running a DFS from each node independently, which takes O(n^2) time. Its second pass moves the root one edge at a time (shown after the code).

Java
// Pass 2: count[] and ans[0] come from pass 1 (rooted at node 0)void reroot(int u, int parent) {    for (int v : adj.get(u)) {        if (v == parent) continue;        // v's subtree moves 1 closer, the other n - count[v] nodes 1 farther        ans[v] = ans[u] - count[v] + (n - count[v]);        reroot(v, u);    }}

The rerooting technique reduces this to O(n) via two DFS passes. Pass 1 computes subtree sizes and distance sums rooted at arbitrary node 0.

Pass 2 moves the root from parent u to neighbor v. Moving to v moves all nodes in v's subtree 1 unit closer (-count[v]) and all remaining (n - count[v]) nodes 1 unit farther: ans[v] = ans[u] - count[v] + (n - count[v]).

Next step

Check your understanding

10 quick questions