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.
Test Cases
Input:
(TreeNode) root = [3,2,3,null,3,null,1]
Output:
Explanation:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int rob ( TreeNode * root ) {
vector < int > res = robSub ( root );
return max ( res [ 0 ], res [ 1 ]);
}
vector < int > robSub ( TreeNode * root ) {
vector < int > res ( 2 , 0 );
if ( root == nullptr ) {
return res ;
}
vector < int > left = robSub ( root -> left );
vector < int > right = robSub ( root -> right );
res [ 0 ] = max ( left [ 0 ], left [ 1 ]) + max ( right [ 0 ], right [ 1 ]);
res [ 1 ] = root -> val + left [ 0 ] + right [ 0 ];
return res ;
}
};
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rob ( TreeNode root ) {
int [] res = robSub ( root );
return Math . max ( res [ 0 ], res [ 1 ]);
}
private int [] robSub ( TreeNode root ) {
if ( root == null ) return new int [ 2 ];
int [] left = robSub ( root . left );
int [] right = robSub ( root . right );
int [] res = new int [ 2 ];
res [ 0 ] = Math . max ( left [ 0 ], left [ 1 ]) + Math . max ( right [ 0 ], right [ 1 ]);
res [ 1 ] = root . val + left [ 0 ] + right [ 0 ];
return res ;
}
}
from typing import Optional
# Definition for a binary tree node.
class TreeNode :
def __init__ ( self , val = 0 , left = None , right = None ):
self . val = val
self . left = left
self . right = right
class Solution :
def rob ( self , root : Optional [ TreeNode ]) -> int :
res = self . robsub ( root )
return max ( res [ 0 ], res [ 1 ])
def robsub ( self , root ):
if not root :
return [ 0 , 0 ]
left = self . robsub ( root . left )
right = self . robsub ( root . right )
res = [ 0 , 0 ]
res [ 0 ] = max ( left [ 0 ], left [ 1 ]) + max ( right [ 0 ], right [ 1 ])
res [ 1 ] = root . val + left [ 0 ] + right [ 0 ]
return res
Time Complexity: O(n)
Space Complexity: O(1)