Skip to content

Commit cbd0022

Browse files
authored
Create 337. House Robber III
1 parent 92ebbd1 commit cbd0022

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

337. House Robber III

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
Map<TreeNode,Integer> map=new HashMap<>();
18+
public int rob(TreeNode root) {
19+
if(root==null){
20+
return 0;
21+
}
22+
if(map.containsKey(root)){
23+
return map.get(root);
24+
}
25+
26+
int sum=root.val;
27+
28+
if(root.left!=null){
29+
sum+=rob(root.left.left);
30+
sum+=rob(root.left.right);
31+
}
32+
33+
if(root.right!=null){
34+
sum+=rob(root.right.left);
35+
sum+=rob(root.right.right);
36+
}
37+
38+
int next_sum=rob(root.left)+rob(root.right);
39+
40+
int res=Math.max(sum,next_sum);
41+
map.put(root,res);
42+
return res;
43+
}
44+
}

0 commit comments

Comments
 (0)