337-House-Robber-III
Last updated
Last updated
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private class Info{
int rob;
int noRob;
Info(){};
Info(int rob,int noRob){
this.rob=rob;
this.noRob=noRob;
}
};
public int rob(TreeNode root) {
if(root==null){
return 0;
}
Info result=recur(root);
return Math.max(result.rob,result.noRob);
}
private Info recur(TreeNode root){
if(root.left==null && root.right==null){
return new Info(root.val,0);
}
Info left=root.left!=null?recur(root.left):new Info(0,0);
Info right=root.right!=null?recur(root.right):new Info(0,0);
Info current=new Info(0,0);
//偷当前节点,只能与下一层不偷的收益做计算
current.rob=root.val+left.noRob+right.noRob;
// current.noRob=Math.max(left.rob+right.rob,current.noRob);
// current.noRob=Math.max(left.noRob+right.noRob,current.noRob);
// current.noRob=Math.max(left.rob+right.noRob,current.noRob);
// current.noRob=Math.max(left.noRob+right.rob,current.noRob);
//不偷当前节点,选择下一层偷和不偷较高收益和当前节点利益计算
current.noRob+=Math.max(left.rob,left.noRob);
current.noRob+=Math.max(right.rob,right.noRob);
//返回当前层的信息
return current;
}
}