-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path337. House Robber III.java
43 lines (42 loc) · 1.15 KB
/
337. House Robber III.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int rob(TreeNode root) {
if (root == null) return 0;
this.rob(root.left);
this.rob(root.right);
int robRoot = root.val;
if (root.left != null) {
if (root.left.left != null) {
robRoot += root.left.left.val;
}
if (root.left.right != null) {
robRoot += root.left.right.val;
}
}
if (root.right != null) {
if (root.right.left != null) {
robRoot += root.right.left.val;
}
if (root.right.right != null) {
robRoot += root.right.right.val;
}
}
int notRobRoot = 0;
if (root.left != null) {
notRobRoot += root.left.val;
}
if (root.right != null) {
notRobRoot += root.right.val;
}
root.val = (robRoot > notRobRoot) ? robRoot : notRobRoot;
return root.val;
}
}