Skip to content

Commit 50f293d

Browse files
house robber III
1 parent 89a68de commit 50f293d

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Common/src/classes/TreeNode.java

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package classes;
2+
3+
public class TreeNode {
4+
public int val;
5+
public TreeNode left;
6+
public TreeNode right;
7+
public TreeNode(int x){this.val = x;}
8+
}

MEDIUM/src/medium/HouseRobberIII.java

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package medium;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
import classes.TreeNode;
7+
8+
public class HouseRobberIII {
9+
10+
//simple recursion without cacheing: 1189 ms
11+
public int rob(TreeNode root) {
12+
if(root == null) return 0;
13+
14+
int val = 0;
15+
if(root.left != null){
16+
val += rob(root.left.left) + rob(root.left.right);
17+
}
18+
if(root.right != null){
19+
val += rob(root.right.left) + rob(root.right.right);
20+
}
21+
val = Math.max(val + root.val, rob(root.left) + rob(root.right));
22+
return val;
23+
}
24+
25+
//same idea, but with cacheing via a hashmap: 8 ms
26+
public int rob_dp(TreeNode root) {
27+
Map<TreeNode, Integer> map = new HashMap<TreeNode, Integer>();
28+
return get(root, map);
29+
}
30+
31+
private int get(TreeNode root, Map<TreeNode, Integer> map){
32+
if(root == null) return 0;
33+
if(map.containsKey(root)) return map.get(root);
34+
35+
int val = 0;
36+
if(root.left != null) val += get(root.left.left, map) + get(root.left.right, map);
37+
if(root.right != null) val += get(root.right.left, map) + get(root.right.right, map);
38+
int max = Math.max(root.val + val, get(root.left, map) + get(root.right, map));
39+
map.put(root, max);
40+
return max;
41+
}
42+
43+
44+
}

0 commit comments

Comments
 (0)