Trees & BST · Pattern 6 of 12
Postorder with multiple return values: tree DP
Solve both children first, then the node. Each call returns what its parent needs (height, a sum, a pair of states), and the real answer is often recorded on the side.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- The answer for a node depends on answers from both subtrees
- A path that bends at some node (diameter, max path sum)
- Return two or more facts at once: is it balanced and how tall, is it a BST and its min and max
- Choose or skip each node with a parent-child rule (robber, cameras)
The template
// diameter: return the height to the parent, record the best path through each node
int best;
int diameterOfBinaryTree(TreeNode root) {
best = 0;
height(root);
return best;
}
int height(TreeNode node) {
if (node == null) return 0;
int l = height(node.left), r = height(node.right); // children first
best = Math.max(best, l + r); // record: the path bending here
return 1 + Math.max(l, r); // return: the longer arm
}
// House Robber III: return two values {best if robbed, best if skipped}
int rob(TreeNode root) {
int[] r = robBoth(root);
return Math.max(r[0], r[1]);
}
int[] robBoth(TreeNode node) {
if (node == null) return new int[]{0, 0};
int[] l = robBoth(node.left), r = robBoth(node.right);
int take = node.val + l[1] + r[1]; // then both children are skipped
int skip = Math.max(l[0], l[1]) + Math.max(r[0], r[1]);
return new int[]{take, skip};
} # diameter: return the height to the parent, record the best path through each node
def diameter_of_binary_tree(root):
best = 0
def height(node):
nonlocal best
if not node:
return 0
l, r = height(node.left), height(node.right) # children first
best = max(best, l + r) # record: the path bending here
return 1 + max(l, r) # return: the longer arm
height(root)
return best
# House Robber III: return two values (best if robbed, best if skipped)
def rob(root):
def both(node):
if not node:
return 0, 0
lt, ls = both(node.left)
rt, rs = both(node.right)
take = node.val + ls + rs # then both children are skipped
skip = max(lt, ls) + max(rt, rs)
return take, skip
return max(both(root)) // diameter: return the height to the parent, record the best path through each node
int height(TreeNode* node, int& best) {
if (!node) return 0;
int l = height(node->left, best), r = height(node->right, best); // children first
best = max(best, l + r); // record: the path bending here
return 1 + max(l, r); // return: the longer arm
}
int diameterOfBinaryTree(TreeNode* root) {
int best = 0;
height(root, best);
return best;
}
// House Robber III: return two values {best if robbed, best if skipped}
pair<int, int> robBoth(TreeNode* node) {
if (!node) return {0, 0};
auto [lt, ls] = robBoth(node->left);
auto [rt, rs] = robBoth(node->right);
int take = node->val + ls + rs; // then both children are skipped
int skip = max(lt, ls) + max(rt, rs);
return {take, skip};
}
int rob(TreeNode* root) {
auto [take, skip] = robBoth(root);
return max(take, skip);
} // diameter: return the height to the parent, record the best path through each node
function diameterOfBinaryTree(root) {
let best = 0;
function height(node) {
if (!node) return 0;
const l = height(node.left), r = height(node.right); // children first
best = Math.max(best, l + r); // record: the path bending here
return 1 + Math.max(l, r); // return: the longer arm
}
height(root);
return best;
}
// House Robber III: return two values [best if robbed, best if skipped]
function rob(root) {
function both(node) {
if (!node) return [0, 0];
const [lt, ls] = both(node.left), [rt, rs] = both(node.right);
const take = node.val + ls + rs; // then both children are skipped
const skip = Math.max(lt, ls) + Math.max(rt, rs);
return [take, skip];
}
return Math.max(...both(root));
} The variations
-
1Return the height, record the best
Each call returns one number upward (the height or the best one-arm path) and updates a global answer with the path that bends at this node.
Now you solve -
2Return several facts at once
Validate a BST by returning (is it a BST, min, max) for each subtree. The largest BST adds the size, so a parent can tell whether it extends both children.
Now you solve- Largest BST Medium Stuck? ▶ video
-
3Return a sum or a count
Return the subtree sum or size. Children sum compares the node with it; distribute coins returns the extra coins (
coins - nodes), and every unit that crosses an edge is one move; the highest score multiplies the sizes of the parts.Now you solve -
4Return a state per node
Return a small set of states: (robbed, skipped) for the robber, or (has a camera, is covered, needs cover) for cameras. Each node picks from its children's states. This is DP on a tree.
Now you solve- House Robber III Medium Stuck? solution
-
5Decide after the children are done
Return the height from the bottom (leaves are 0) to group nodes into leaf layers. To delete nodes, let each call return the subtree that is left and add a node to the forest when its parent is deleted.
Now you solve
Mistakes to avoid
- Returning the bent path (left + right) to the parent: a parent can only extend one arm, so return
1 + max(l, r)and record the bent one. - Max path sum: negative arms should count as 0, but the answer must still start from at least one node, so begin
bestat the smallest value, not 0. - Calling height inside an isBalanced recursion: that is O(n²). Return the height and a "not balanced" signal (like -1) in one pass.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.