Redefine rob(root)
as a new function which will return an array of two elements, the first
element of which denotes the maximum amount of money that can be robbed if root
is not
robbed, while the second element signifies the maximum amount of money robbed if it is robbed.
Let's relate rob(root)
to rob(root.left)
and rob(root.right)...
,
etc. For the 1st element of rob(root)
, we only need to sum up the larger elements of rob(root.left)
and rob(root.right)
,
respectively, since root
is not robbed and we are free to rob its left and right subtrees.
For the 2nd element of rob(root)
, however, we only need to add up the 1st elements of rob(root.left)
and rob(root.right)
,
respectively, plus the value robbed from root
itself, since in this case it's guaranteed
that we cannot rob the nodes of root.left
and root.right
.
定义rob(root) 返回一个有两个元素的数组。
第一个数表示: 如果root没有被抢, 最大的金钱
第一个数表示: 如果root被抢,最大的金钱
怎样把rob(root) 联系上 rob(root.left) 或是 rob(root.right)?
rob(root)的第一个数等于 rob(root.left) 和 rob(root.right) 较大的, 因为root 没有被抢,我们随意可以抢左右子树。
rob(root)的第二个数等于 rob(root.left) 和 rob(root.right) 的第一个数的和加上 root.val
public int rob(TreeNode root) {
int[] res = robSub(root);
return Math.max(res[0], res[1]);
}
private int[] robSub(TreeNode root) {
if (root == null) return new int[2];
int[] left = robSub(root.left);
int[] right = robSub(root.right);
int[] res = new int[2];
res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
res[1] = root.val + left[0] + right[0];
return res;
}