House Robber III - Problem
You are a professional thief who has discovered a unique neighborhood where all the houses are arranged in a binary tree structure. Each house contains a certain amount of money, but there's a catch: the houses have a sophisticated security system that will automatically alert the police if two directly connected houses (parent-child relationship) are robbed on the same night.
Given the root of a binary tree where each node represents a house with a certain amount of money, determine the maximum amount of money you can rob without triggering the alarm system.
Goal: Find the maximum sum of money you can steal without robbing any two directly connected houses in the tree.
Input & Output
example_1.py โ Basic Binary Tree
$
Input:
root = [3,2,3,null,3,null,1]
โบ
Output:
7
๐ก Note:
Maximum money robbed = 3 + 3 + 1 = 7. We rob houses with values 3 (root), 3 (left-right), and 1 (right-right), avoiding adjacent nodes.
example_2.py โ Deeper Tree
$
Input:
root = [3,4,5,1,3,null,1]
โบ
Output:
9
๐ก Note:
Maximum money robbed = 4 + 5 = 9. We rob houses 4 (left child) and 5 (right child), which gives us the maximum without robbing adjacent nodes.
example_3.py โ Single Node
$
Input:
root = [5]
โบ
Output:
5
๐ก Note:
With only one house, we rob it and get 5. No adjacent constraint applies.
Constraints
-
The number of nodes in the tree is in the range
[0, 104] -
0 โค Node.val โค 104 - Tree structure: Each node has at most two children
- No negative values in the tree
Visualization
Tap to expand
Understanding the Visualization
1
Identify the choice
At each house, decide: rob this house or skip it
2
Calculate scenarios
Rob current + best from grandchildren vs Skip current + best from children
3
Use memoization
Cache results to avoid recalculating the same subtrees
4
Propagate upward
Combine optimal choices from bottom to top
Key Takeaway
๐ฏ Key Insight: At each node, we have exactly two choices. The optimal solution combines the best choice at each level using dynamic programming to avoid redundant calculations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code