Skip to content

Commit 145b68d

Browse files
Sean PrashadSean Prashad
Sean Prashad
authored and
Sean Prashad
committed
Add 337_House_Robber_III.java
1 parent d67d4fb commit 145b68d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public int rob(TreeNode root) {
3+
return helper(root, new HashMap<TreeNode, Integer>());
4+
}
5+
6+
private int helper(TreeNode root, Map<TreeNode, Integer> m) {
7+
if (root == null) {
8+
return 0;
9+
}
10+
if (m.containsKey(root)) {
11+
return m.get(root);
12+
}
13+
14+
int result = 0;
15+
16+
if (root.left != null) {
17+
result += helper(root.left.left, m) + helper(root.left.right, m);
18+
}
19+
20+
if (root.right != null) {
21+
result += helper(root.right.left, m) + helper(root.right.right, m);
22+
}
23+
24+
result = Math.max(result + root.val, helper(root.left, m) + helper(root.right, m));
25+
m.put(root, result);
26+
return result;
27+
}
28+
}

0 commit comments

Comments
 (0)