/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int rob(TreeNode root) {
if(root == null) {
return 0;
}
//左孩子节点能偷的最大金额
int leftMoney = rob(root.left);
//右孩子节点能偷的最大金额
int rightMoney = rob(root.right);
//左孩子的左孩子节点能偷的最大金额
int leftChildLeftMoney = 0;
//左孩子的右孩子节点能偷的最大金额
int leftChildRightMoney = 0;
//右孩子的左孩子节点能偷的最大金额
int rightChildLeftMoney = 0;
//右孩子的右孩子节点能偷的最大金额
int rightChildRightMoney = 0;
if(root.left != null) {
leftChildLeftMoney = rob(root.left.left);
leftChildRightMoney = rob(root.left.right);
}
if(root.right != null) {
rightChildLeftMoney = rob(root.right.left);
rightChildRightMoney = rob(root.right.right);
}
//比较第一层孩子节点的金额总和与第二层所有孩子节点金额总和加上当前节点金额的最大值,即为结果
return Math.max(leftMoney + rightMoney, root.val + leftChildLeftMoney + leftChildRightMoney + rightChildLeftMoney + rightChildRightMoney);
}
}