House Robber III
medium
dynamic-programming
binary-tree
depth-first-search
tree
The houses in this neighborhood form a binary tree: the root is one house, and each node's children are the houses directly connected to it. The alarm rings only if two directly-linked houses (a parent and one of its children) are robbed on the same night.
Given the root of the tree, return the maximum amount of money you can rob without alerting the police.
Input / output
- Input:
root: TreeNode(the JSON test fixture is a LeetCode-style level-order array usingnullfor missing children, for example[3,2,3,null,3,null,1]) - Output:
int(maximum loot)
Examples
root = [3,2,3,null,3,null,1]returns7by robbing the root and both grandchildren (3 + 3 + 1).root = [3,4,5,1,3,null,1]returns9by robbing the two children (4 + 5).root = [4]returns4.
Constraints
0 <= number of nodes <= 10^40 <= Node.val <= 10^4
Follow-up
A naive recursion recomputes grandchildren repeatedly. Can you make each node return both "best if I rob this node" and "best if I skip it" so the whole tree is solved in a single O(n) postorder pass?
Examples
Example 1
Input: root = [3,2,3,null,3,null,1]
Output: 7
Example 2
Input: root = [3,4,5,1,3,null,1]
Output: 9
Example 3
Input: root = [4]
Output: 4