Maximum Sum of nodes in Binary tree such that no two are adjacent
Pattern: Tree DP basics
Choose nodes with no parent and child both chosen, for the largest sum. Each node returns two numbers: the best total with it taken (its children then must be skipped) and with it skipped (each child may be taken or not).
The problem
Return the largest sum of a set of nodes in which no two are directly connected (no parent with its child). Values are
non-negative. [1, 2, 3, 4, null, 5, 6] gives 16. LeetCode's House Robber III is the same task. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- If a node is taken, what is forbidden?
- If it is skipped, what may its children do?
- What two numbers should each node report?
Hints
Brute force, and why it fails
Try every set of nodes: O(2ⁿ × n). The tests use this for small trees.
The key insight
Two numbers per node capture the only thing a parent needs to know, so one post-order pass solves it.
Dry run
Tree [1, 2, 3, 4, null, 5, 6]. Leaves 4, 5, 6 return (taken, skipped) = (value, 0).
The plan
best(n): if null: (0, 0)
(lt, ls) = best(left); (rt, rs) = best(right)
take = n.val + ls + rs
skip = max(lt, ls) + max(rt, rs)
return (take, skip)
Complexity
- Time
O(n)- Space
O(h)
One post-order pass.
Edge cases
- One node: its value.
- A chain: like House Robber on a line.
- Empty tree: 0.
I've built my logic, show the code
Java
class Solution {
public int getMaxSum(TreeNode root) {
int[] r = best(root);
return Math.max(r[0], r[1]);
}
private int[] best(TreeNode n) { // {best with n taken, best with n left out}
if (n == null) return new int[]{0, 0};
int[] l = best(n.left), r = best(n.right);
int take = n.val + l[1] + r[1]; // taking n rules out its children
int skip = Math.max(l[0], l[1]) + Math.max(r[0], r[1]); // leaving n out frees them
return new int[]{take, skip};
}
}C++
class Solution {
public:
int getMaxSum(TreeNode* root) {
pair<int, int> r = best(root);
return max(r.first, r.second);
}
pair<int, int> best(TreeNode* n) { // {best with n taken, best with n left out}
if (n == NULL) return make_pair(0, 0);
pair<int, int> l = best(n->left), r = best(n->right);
int take = n->val + l.second + r.second; // taking n rules out its children
int skip = max(l.first, l.second) + max(r.first, r.second); // leaving n out frees them
return make_pair(take, skip);
}
};Python
class Solution:
def getMaxSum(self, root) -> int:
def best(n): # (best with n taken, best with n left out)
if n is None:
return 0, 0
lt, ls = best(n.left)
rt, rs = best(n.right)
return n.val + ls + rs, max(lt, ls) + max(rt, rs) # taking n rules out its children
return max(best(root))Common mistakes
- Taking grandchildren only, which misses better choices further down.
- Using one number per node.