LeetCode OJ 337. House Robber III

时间:2023-03-08 20:39:14

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.

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

对于这个题目我们有什么思路呢?我们从根节点开始有两种选择,要么偷取根节点的值,要么不偷取根节点。偷取根节点的话,我们接下来只能偷取根节点孩子节点的孩子节点。如果不偷取根节点的话,我们可以直接偷取根节点的孩子节点。然后我们把这两种方式得到的值进行比较,取较大的那个。因此这是一个递归的过程:

rob(root) = max{rob(root.left) + rob(root.rght), root.val + rob(root.left.left) + rob(root.left.right) + rob(root.right.left) + rob(root.right.right)}

if(root == null) rob(root) = 0;

if(root.left == null && root.right == null) rob(root) = root.val

有了上面的递归表达式,我们就很容易进行编程啦!代码如下:

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int rob(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) return root.val;
int maxnum1 = 0;
int maxnum2 = 0;
maxnum1 = rob(root.left) + rob(root.right);
if(root.left != null || root.right != null){
int num1 = root.left!=null?rob(root.left.left) + rob(root.left.right):0;
int num2 = root.right!=null?rob(root.right.left) + rob(root.right.right):0;
maxnum2 = num1 + num2 + root.val;
}
return maxnum1>maxnum2?maxnum1:maxnum2;
}
}