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:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
即如何从树中选择几个节点,在确保这几个节点不直接相连的情况下使其值的和最大。
最开始的思路我是采用自顶向下递归遍历树的形式来计算可能获得的最大收益。当前节点的情况有两种:选中或是没选中,如果选中的话,那么两个直接子节点将不可以被选中,如果没选中,那么两个直接子节点的状态可以是选中或是没选中。代码如下:
public int rob(TreeNode root) {
if(root == null) return 0;
int result1 = root.val + (root.left == null ? 0 : rob(root.left.left) + rob(root.left.right)) + (root.right == null ? 0 : rob(root.right.left) + rob(root.right.right));
int result2 = rob(root.left) + rob(root.right);
return Math.max(result1, result2);
}
这段代码的缺陷在于,我需要遍历这棵树两次,分别为了获取选中当前节点和不选中当前节点的情况。而事实上我们可以在一次遍历中就得到这两个情况对于当前节点的影响,并通过递归将值传递回上一层。很像是一种逆向思维。
public int rob2(TreeNode root) {
if (root == null) return 0;
int[] value = robSum(root);
return Math.max(value[0], value[1]);
}
private int[] robSum(TreeNode root) {
int[] res = new int[2];
if (root == null) return res;
int[] left = robSum(root.left);
int[] right = robSum(root.right);
res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
res[1] = root.val + left[0] + right[0];
return res;
}