House Robber III

The houses in a neighborhood form a binary tree whose root is the only entrance. Each house holds some money. If two directly linked houses (a parent and its child) are both robbed on the same night, the police are alerted. Given the root, return the maximum amount of money the thief can rob without alerting the police.

30:00

House Robber III
medium
Free written solution
Topics
Companies

The houses in a neighborhood form a binary tree whose root is the only entrance. Each house holds some money. If two directly linked houses (a parent and its child) are both robbed on the same night, the police are alerted. Given the root, return the maximum amount of money the thief can rob without alerting the police.

Example 1:
Input: {"root":[3,2,3,null,3,null,1]}
Output: 7
Constraints:
  • The number of nodes in the tree is in the range [1,104][1, 10^4].

  • 0≤Node.val≤1040 \leq \text{Node.val} \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[3,2,3,null,3,null,1]}

Each house will get a pair: take = best loot if it is robbed, skip = best loot if it is not. Start dfs at the root 3.

3T?S?2T?S?3T?S?3T?S?1T?S?

pairs computed: 0 of 5

T = rob this house
S = leave it
current / child values used
open dfs calls
robbed in the best plan
Variables
VariableValue
nodenull
DepthFunction Call
Stack empty
0/20