House Robber III Problem
Description
LeetCode Problem 337.
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.
Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.
Example 1:
Input: root = [3,2,3,null,3,null,1]
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
Input: root = [3,4,5,1,3,null,1]
Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.
Constraints:
- The number of nodes in the tree is in the range [1, 10^4].
- 0 <= Node.val <= 10^4
Solution
Approach: Tree DP with Two Values per Node
A greedy choice such as "rob every other level" fails: in [2,1,3,null,4] the best is 4 + 3 = 7, which takes one node from level 1 and one from level 2. We need to decide node by node, and a node's decision depends only on its children.
So for every node, compute two numbers about its subtree with one post-order traversal:
rob_here: the most money if we rob this node. Its children must then be skipped:node.val + left_skip + right_skip.skip_here: the most money if we skip this node. Each child is then free, so take the better of its two values:max(left_rob, left_skip) + max(right_rob, right_skip).
An empty child returns (0, 0). The answer is the larger of the two values at the root.
Returning both values from each call is the key detail. The common simpler recursion, rob(node) = max(node.val + rob(grandchildren), rob(children)), computes the same answer but calls rob on each grandchild again from its grandparent, and without memoization the running time becomes exponential on deep trees. With the pair, every node is visited exactly once.
Complexity: O(n) time, where n is the number of nodes, and O(h) space for the recursion, where h is the height of the tree.
class Solution:
def rob(self, root: Optional[TreeNode]) -> int:
def best(node: Optional[TreeNode]) -> Tuple[int, int]:
"""(most money if we rob node, most money if we skip node) in node's subtree."""
if node is None:
return 0, 0
left_rob, left_skip = best(node.left)
right_rob, right_skip = best(node.right)
# Robbing node: its children must be skipped.
rob_here = node.val + left_skip + right_skip
# Skipping node: each child is free to be robbed or skipped, whichever is better.
skip_here = max(left_rob, left_skip) + max(right_rob, right_skip)
return rob_here, skip_here
return max(best(root))
Now write it from memory
Close the write-up and solve it yourself against the tests.