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
32331ROB STRATEGYRob: 3 + 3 + 1 = 7Skip: 2 + 3 = 5Choose: ROB (7)Green dashed circles show optimal houses to rob (total: 7)
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.
Asked in
Amazon 45 Google 38 Meta 32 Microsoft 28 Apple 22
68.2K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen