DP on trees: each node passes up two answers
🌍 In real life. A company's org chart is a tree, and the office party has a rule: nobody comes together with their direct boss (the evening wouldn't be fun). Each person has a "fun score". Which people should be invited for the most fun? A thief who can't rob two houses joined by a road, in a village whose roads form a tree, faces the same question (LeetCode 337, House Robber III).
In Lesson 57.3 the houses were in a row, and the DP went left to right. On a tree, the DP goes bottom up: each node works out its answer from its children's, in postorder.
The idea in one sentence: for each node, work out two best values, one if the node is taken and one if it isn't, using only its children's pairs, and the root's better value is the answer.
Its words:
- tree DP: a DP whose subproblems are subtrees, filled in postorder
- state with a flag: one value per choice at the node (taken / not taken), passed up as a pair
- independent set: chosen nodes, no two joined by an edge; the robber wants the heaviest one
Step by step, at one node:
- Ask each child for its pair (with, without).
- Taken: the children must be left out:
val + left_without + right_without. - Not taken: each child is free to be taken or not:
max(left pair) + max(right pair). - Pass the pair up. An empty child gives (0, 0).
The answers come back in postorder, children before parents:
Why it is correct. For the best choice inside a subtree, the only thing the rest of the tree needs to know is whether the subtree's root was taken (that decides whether its parent may be taken). So two numbers per node carry everything; within each case, each child's subtree is best on its own, and adding them up is right because subtrees don't share nodes.
What it costs, by counting. One visit per node, constant work: O(n) time, O(h) for the recursion. Trying every subset of nodes is O(2ⁿ); and recursion that asks "rob the grandchildren?" without returning pairs visits nodes many times over.
The same shape everywhere. Change the two cases and the combine rule and the method solves many tree problems: fewest guards so that every road has a guard at one end (minimum vertex cover), the largest group with no boss–employee pairs, the diameter (Lesson 47.4), the maximum path sum (Lesson 47.5).
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def rob(root):
def best(node): # (best with node taken, best without it)
if node is None:
return 0, 0
lw, lo = best(node.left)
rw, ro = best(node.right)
with_it = node.val + lo + ro # taken: its children must be left out
without = max(lw, lo) + max(rw, ro) # left out: each child chooses freely
return with_it, without
return max(best(root))
def min_guards(root):
def best(node): # (fewest guards with one here, without)
if node is None:
return float("inf"), 0 # no node: can't guard it, costs nothing
lg, ln = best(node.left)
rg, rn = best(node.right)
with_guard = 1 + min(lg, ln) + min(rg, rn)
without = (lg if node.left else 0) + (rg if node.right else 0)
return with_guard, without # without: every child edge needs the child
return min(best(root)) if root else 0
print(rob(Node(10, Node(1, Node(20), Node(4)), Node(2, None, Node(30)))))
print(rob(Node(3, Node(2, None, Node(3)), Node(3, None, Node(1)))))
print(min_guards(Node(1, Node(2, Node(3), Node(4)))), min_guards(Node(1, Node(2, Node(3, Node(4))))))Mistakes and edge cases.
- Taking a node with its children.
val + left_with + right_withlets two neighbours be robbed: the answer comes out too big. - Forcing children in when a node is left out. Leaving a node out doesn't mean its children must be taken; let each choose the better of its pair.
- Returning one number and recursing into grandchildren. It works but visits nodes again and again; the pair visits each once.
- The empty tree.
max(best(None))ismax(0, 0) = 0; for problems like guards, decide what "no node" means (inffor "can't guard what isn't there"). - Deep trees. Like every recursive tree walk, a chain thousands of nodes deep needs your own stack (Lesson 47.7).
Quiz
What does this print?
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def rob(root): def best(node): # (best with node taken, best without it) if node is None: return 0, 0 lw, lo = best(node.left) rw, ro = best(node.right) with_it = node.val + lo + ro # taken: its children must be left out without = max(lw, lo) + max(rw, ro) # left out: each child chooses freely return with_it, without return max(best(root)) print(rob(Node(3, Node(4, Node(1), Node(3)), Node(5, None, Node(1)))))Why does each node return two numbers instead of one?
- Its parent needs to know the best both when this node is taken and when it isn't
- To count the nodes
- Because a tree has two sides
What does the robber's tree DP cost on a tree of n nodes?
- O(n): each node is visited once, with constant work
- O(2ⁿ)
- O(n²)
For the tree Node(10, Node(1, Node(20), Node(4)), Node(2, None, Node(30))) the answer should be 64, but this gives 67. Which line is wrong?
def rob(root): def best(node): if node is None: return 0, 0 lw, lo = best(node.left) rw, ro = best(node.right) with_it = node.val + lw + rw without = max(lw, lo) + max(rw, ro) return with_it, without return max(best(root))
Coding tasks
Write
rob(root): the biggest total of node values you can take with no two taken nodes joined by an edge.Write
min_guards(root): the fewest nodes to put a guard on so that every edge of the tree has a guard at one end or both. An empty tree or a single node needs 0.