-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHOUSEROBBERIII.java
More file actions
39 lines (39 loc) · 1.08 KB
/
HOUSEROBBERIII.java
File metadata and controls
39 lines (39 loc) · 1.08 KB
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
static class Pair{
int include;
int exclude;
public Pair(int i,int e){
this.include=i;
this.exclude=e;
}
}
public int rob(TreeNode root) {
Pair result=helper(root);
return Math.max(result.include,result.exclude);
}
public static Pair helper(TreeNode root){
if(root==null){
return new Pair(0,0);
}
Pair leftChild=helper(root.left);
Pair rightChild=helper(root.right);
int include=root.val+leftChild.exclude+rightChild.exclude;
int exclude=Math.max(leftChild.include,leftChild.exclude)+Math.max(rightChild.include,rightChild.exclude);
return new Pair(include,exclude);
}
}