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
House Robber III - Binary Tree DP INPUT: Binary Tree 3 2 3 3 1 Each node = House with money root = [3,2,3,null,3,null,1] Cannot rob adjacent houses! (parent-child are linked) ALGORITHM: DFS Bottom-Up 1 DFS to Leaves Traverse bottom-up 2 Track Two States [rob_curr, skip_curr] 3 Compute Each Node Compare rob vs skip 4 Return Max max(rob, skip) at root rob = node.val + left[1] + right[1] skip = max(left) + max(right) Example at node 2: left child(3): [3, 0] rob = 2 + 0 = 2 skip = 3 --> [2, 3] FINAL RESULT 3 ROB 2 SKIP 3 SKIP 3 ROB 1 ROB Robbed: 3 + 3 + 1 = 7 Skipped: 2 + 3 = 5 Output: 7 = Robbed Key Insight: Each node returns TWO values: [max if robbed, max if skipped]. This enables O(n) time by avoiding recomputation. If we rob current node, we MUST skip children. If we skip current, we take the best option for each child independently. Post-order DFS ensures children processed first. TutorialsPoint - House Robber III | Optimal DFS (Bottom-Up State Tracking) Time Complexity: O(n) | Space Complexity: O(h) where h = tree height
Asked in
Amazon 15 Facebook 12 Google 8 Microsoft 6
185.0K Views
High Frequency
~25 min Avg. Time
2.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