Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b545e40

Browse files
Add Solution2.java to problems 0337
1 parent 71ddb3a commit b545e40

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
12+
Map<TreeNode, Integer> memo = new HashMap<>();
13+
14+
public int rob(TreeNode root) {
15+
if (root == null) return 0;
16+
17+
if (memo.containsKey(root))
18+
return memo.get(root);
19+
20+
int do_it = root.val
21+
+ (root.left == null ? 0 : rob(root.left.left) + rob(root.left.right))
22+
+ (root.right == null ? 0 : rob(root.right.left) + rob(root.right.right));
23+
24+
int not_do = rob(root.left) + rob(root.right);
25+
26+
int res = Math.max(do_it, not_do);
27+
memo.put(root, res);
28+
return res;
29+
}
30+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
class Solution {
11+
public int rob(TreeNode root) {
12+
int[] res = solution(root);
13+
return Math.max(res[0], res[1]);
14+
}
15+
16+
private int[] solution(TreeNode root) {
17+
if (root == null) return new int[]{0, 0};
18+
int[] left = solution(root.left);
19+
int[] right = solution(root.right);
20+
21+
int rob = root.val + left[1] + right[1];
22+
int notRob = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
23+
return new int[]{rob, notRob};
24+
}
25+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /