House Robber III
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trees.
House Robber III
Tree robbery.
Approach 1
Level I: Brute Force Recursion
Intuition
Each node can either be robbed or not robbed. If we rob a node, we cannot rob its direct children. If we don't rob it, we can either rob its children or not.
Logic
rob(root) = max(root.val + rob(left.left) + rob(left.right) + rob(right.left) + rob(right.right), rob(left) + rob(right)).⏱ O(2^N) (Exponential overlapping subproblems)💾 O(H)
Detailed Dry Run
At root: Option 1 (Rob 1 + grandchildren). Option 2 (Rob children 2 and 3). Max is 3.
Approach 2
Level II: Memoization
Intuition
We can store the result of
rob(node) in a HashMap to avoid recomputing for the same node multiple times.⏱ O(N)💾 O(N)
Detailed Dry Run
Store [Node Pointer] -> Max rob value.
Approach 3
Level III: Optimal (Post-order DP Pair)
Intuition
Each node returns a pair:
[max if robbed, max if NOT robbed].- If we rob
root, we must NOT rob its children:root.val + left[1] + right[1]. - If we DON'T rob
root, we take the max of robbing or not robbing each child:max(left) + max(right).
⏱ O(N)💾 O(H)
Detailed Dry Run
Leaf returns [val, 0]. Parent returns [parentVal + 0, leafVal + 0].
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.