Tree DP basics
Tree dynamic programming computes, for each node, a small answer from its children's answers in one post-order pass: subtree sums, whether the sum-tree rule holds, or the best total when a node is taken or left out. Rewiring a tree into a list also uses a traversal that remembers the previous node.
How to recognise it
- Each node's answer depends only on its subtrees.
- A choice per node (take it or not) with a rule linking parents and children.
- Rearranging the nodes of a tree into another shape.
Answers from children
| Problem | Each node returns |
|---|---|
| largest subtree sum | its subtree's sum (record the best) |
| sum tree check | its subtree's sum, or a marker that the rule broke |
| convert to a sum tree | its old subtree sum, after writing the children's sums into it |
| no two adjacent | (best with it taken, best with it left out) |
best(n):
if n is null: return (0, 0)
(lt, ls) = best(n.left); (rt, rs) = best(n.right)
take = n.val + ls + rs
skip = max(lt, ls) + max(rt, rs)
return (take, skip)
What a node, a child, a leaf and a level are is on the Structures page.
Rewiring
To turn a tree into a doubly linked list in inorder, walk inorder and keep prev: set prev.right = node and
node.left = prev, then move prev to the node. The first node visited is the head.
Common mistakes
- Recomputing subtree sums from scratch at every node, which is O(n²).
- Overwriting a node's value before its old value has been used.
Problems
- Convert Binary tree into Doubly Linked Listmediumguide ready
- Convert Binary tree into Sum treemediumguide ready
- Find minimum swaps required to convert a Binary tree into BSTmediumguide ready
- Check if Binary tree is Sum tree or notmediumguide ready
- Find Largest subtree sum in a treemediumguide ready
- Maximum Sum of nodes in Binary tree such that no two are adjacentmediumguide ready