Tree DP
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Tree DP solves a problem on a tree, like an org chart or folder structure, by solving each branch first and combining the results at the parent. Each node reports a small summary upwards, such as "best if I am included" and "best if I am not". It is how you optimise anything shaped like a hierarchy.
Practical use cases
- Web app: Company outing invitations. An HR portal has an org chart and wants to invite the largest group to an outing where nobody is invited together with their direct manager. Each employee reports two numbers to their manager: the best group size if they come, and if they do not. The CEO's totals give the answer in one pass over the chart.
- Web app: Folder size and cleanup report. A cloud-storage page shows how much space each folder uses, and a cleanup tool suggests which folders to delete for the biggest saving, where deleting a parent deletes everything inside it. The sizes are computed from the deepest folders upward and combined at each parent.
- System: Network design and family trees. Network planners choose where to place monitors in a tree of devices, and biologists analyse family trees of species. Both combine child results at each parent.
The story: The Wedding Guest Tree
For her cousin's wedding, Mira's family had a strange rule for the sweet-box giveaway. Guests were arranged as a family tree: each person had invited some others under them. "Nobody may get a box if their direct inviter also gets one, or it looks unfair." Each guest's box was worth a different amount of laddoos. How could the family hand out boxes to maximise the total?
Kabir started from the top (the bride's grandfather) but got stuck: taking him blocked two children; skipping him freed them, but whether to take them depended on their children... Mira said, "Start from the bottom. For every guest, compute two numbers: the best total in their little family if they take a box, and the best total if they don't."
A guest at the bottom is easy: take = their own worth, skip = 0. For a parent: take = own worth + the "skip" value of every child; skip = for every child, the better of its take and skip. Each person computes their pair once, using the pairs of their children. At the root, the larger number was 9. This is Tree DP: the DP table is attached to the nodes of a tree and answers flow from the leaves up to the root.
How to spot this problem, and where you need it
Your data is a hierarchy, such as an org chart, category tree or folder structure, and the best choice for a parent depends on the choices made for its children.
Signs you need it
- The problem has a tree and a rule between a parent and its children, like "do not pick both a node and its child".
- Computing an answer for the whole tree needs answers for each subtree first.
- A recursive solution recomputes the same subtree many times because each node is asked two questions, include or exclude.
Where to use it in a project
- Org-chart, category-tree and menu-tree features that optimise a selection with parent-child rules.
- Folder, comment-thread or dependency trees where totals roll up from children to parents.
The solution
Go through the tree from the leaves up, which is a post-order walk. For each node, compute two numbers: the best total if this node is chosen, which is its own value plus the sum of each child's not-chosen value, and the best total if it is not chosen, which is the sum of each child's better of the two. The root's better value is the answer. Each node is visited once.
Payoff: Before: trying every subset of 30 employees, over a billion. After: one visit per employee, 30 small calculations.
Explain it like I am 8
Every person in a family tree whispers two numbers to their parent: "my family's best if I join in" and "my family's best if I stay out". Parents listen to all children, work out their own two numbers and whisper upwards. The grandpa at the top gets the final answer.
How it works, step by step
- Pick a root and visit the tree so that every child is finished before its parent (post-order).
- For each node keep a pair:
takeandskip. - Leaf:
take = value,skip = 0. - Inner node:
take = value + sum(child.skip),skip = sum(max(child.take, child.skip)). - At the root the answer is
max(take, skip).
The code in four languages
PHP
<?php
// Max total value of chosen nodes with no parent and child both chosen.
function bestInvites(array $children, array $value, string $node): array {
$take = $value[$node]; // if we take this node
$skip = 0; // if we skip this node
foreach ($children[$node] as $kid) {
[$kidTake, $kidSkip] = bestInvites($children, $value, $kid); // children finish first
$take += $kidSkip; // taking me forces kids to skip
$skip += max($kidTake, $kidSkip); // skipping me frees each kid
}
return [$take, $skip];
}
$children = ['A' => ['B', 'C'], 'B' => ['D', 'E'], 'C' => ['F'], 'D' => [], 'E' => [], 'F' => []];
$value = ['A' => 3, 'B' => 4, 'C' => 5, 'D' => 1, 'E' => 3, 'F' => 1];
[$t, $s] = bestInvites($children, $value, 'A');
echo max($t, $s), "\n"; // 9JavaScript
// Max total value of chosen nodes with no parent and child both chosen.
function bestInvites(children, value, node) {
let take = value[node]; // if we take this node
let skip = 0; // if we skip this node
for (const kid of children[node]) {
const [kidTake, kidSkip] = bestInvites(children, value, kid); // children finish first
take += kidSkip; // taking me forces kids to skip
skip += Math.max(kidTake, kidSkip); // skipping me frees each kid
}
return [take, skip];
}
const children = { A: ['B', 'C'], B: ['D', 'E'], C: ['F'], D: [], E: [], F: [] };
const value = { A: 3, B: 4, C: 5, D: 1, E: 3, F: 1 };
const [t, s] = bestInvites(children, value, 'A');
console.log(Math.max(t, s)); // 9Java
import java.util.*;
public class Main {
// Max total value of chosen nodes with no parent and child both chosen.
// Returns {take, skip}.
static int[] bestInvites(Map<String, List<String>> children, Map<String, Integer> value, String node) {
int take = value.get(node); // if we take this node
int skip = 0; // if we skip this node
for (String kid : children.get(node)) {
int[] k = bestInvites(children, value, kid); // children finish first
take += k[1]; // taking me forces kids to skip
skip += Math.max(k[0], k[1]); // skipping me frees each kid
}
return new int[]{take, skip};
}
public static void main(String[] args) {
Map<String, List<String>> children = Map.of(
"A", List.of("B", "C"), "B", List.of("D", "E"), "C", List.of("F"),
"D", List.of(), "E", List.of(), "F", List.of());
Map<String, Integer> value = Map.of("A", 3, "B", 4, "C", 5, "D", 1, "E", 3, "F", 1);
int[] r = bestInvites(children, value, "A");
System.out.println(Math.max(r[0], r[1])); // 9
}
}Go
package main
import "fmt"
// bestInvites: max total value of chosen nodes with no parent and child both chosen.
// Returns (take, skip).
func bestInvites(children map[string][]string, value map[string]int, node string) (int, int) {
take := value[node] // if we take this node
skip := 0 // if we skip this node
for _, kid := range children[node] {
kidTake, kidSkip := bestInvites(children, value, kid) // children finish first
take += kidSkip // taking me forces kids to skip
skip += max(kidTake, kidSkip) // skipping me frees each kid
}
return take, skip
}
func main() {
children := map[string][]string{"A": {"B", "C"}, "B": {"D", "E"}, "C": {"F"}, "D": {}, "E": {}, "F": {}}
value := map[string]int{"A": 3, "B": 4, "C": 5, "D": 1, "E": 3, "F": 1}
t, s := bestInvites(children, value, "A")
fmt.Println(max(t, s)) // 9
}Time: O(n) · Extra space: O(h). Every node is visited once; the memory is the depth of the tree (h) from the recursion.
Watch out for
- Processing a parent before its children. The parent needs the children's pairs first.
- Using only one number per node. You need both "take" and "skip" because the parent's choice changes what the child may do.
- Recursing on a very deep tree (like a long chain) without checking the recursion limit.
Quick check
- In what order are nodes finished?
- Parents first
- Children before parents
- Left to right in a list
- If we take a node, what must its children do?
- Take too
- Be skipped
- Choose whichever is better
- What is the final answer?
- take of the root
- skip of the root
- The larger of the root's take and skip