House Robber III - Problem
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.
Input & Output
Example 1 — Basic Tree
$
Input:
root = [3,2,3,null,3,null,1]
›
Output:
7
💡 Note:
Rob nodes 3, 3, and 1 for maximum sum. Cannot rob adjacent nodes (parent-child), so skip the middle level nodes with value 2 and 3.
Example 2 — Simple Tree
$
Input:
root = [3,4,5,1,3,null,1]
›
Output:
9
💡 Note:
Rob nodes 4, 3, and 1 for sum = 4 + 3 + 1 = 8. Or rob nodes 3 and 5 for sum = 3 + 5 = 8. Or rob root 3 and leaves 1,3,1 for sum = 3 + 1 + 3 + 1 = 8. Actually, rob 4 + 5 = 9 is optimal.
Example 3 — Single Node
$
Input:
root = [5]
›
Output:
5
💡 Note:
Only one house to rob, so rob it for value 5.
Constraints
- The number of nodes in the tree is in the range [1, 104]
- 0 ≤ Node.val ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree where each node represents a house with money value
2
Constraint
Cannot rob two directly connected houses (parent-child relationship)
3
Find Maximum
Return maximum money that can be robbed following the constraint
Key Takeaway
🎯 Key Insight: For each node, choose to rob it (skip children) or skip it (consider children) - track both states optimally
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code