Learn / Trees

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

ProblemEach node returns
largest subtree sumits subtree's sum (record the best)
sum tree checkits subtree's sum, or a marker that the rule broke
convert to a sum treeits 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

0 of 6 solved

Check yourself

For 'no two adjacent nodes', what pair does each node return?

Converting a tree to a doubly linked list in inorder, what must you remember during the walk?

Minimum swaps to turn a complete binary tree into a BST: what do you sort?