The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
Input: [3,2,3,null,3,null,1]
3
/ \
2 3
\ \
3 1
Output: 7
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
房间的布局组成一个二叉树,而robber不能同时抢相连的parent和child的房间,问能抢到的最大值是多少
思路:
按照之前robber的思路,两种情况,抢和不抢,也是参考了大神的方法,定义一个长度为2的数组,[0]表示不抢,[1]表示抢。
到一个节点的时候,如果它自身rob,那么子节点就不能rob, 这种情况就是节点[1] = left[0] + right[0] + val
如果节点本身不rob, 那么就是max(left[0], left[1]) + max(right[0], right[1])
public int rob(TreeNode root) {
int[] robVal = helper(root);
return Math.max(robVal[0], robVal[1]);
}
public int[] helper(TreeNode root) {
if (root == null) {
return new int[2];
}
int[] val = new int[2];
int[] left = helper(root.left);
int[] right = helper(root.right);
val[1] = left[0] + right[0] + root.val;
val[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return val;
}