题目要求:
分析:
这是一道树形DP题,之前我说过,遇到树的题目,就要想到用递归,这道题目也一样,并且也要使用DP。
我们令dp来表示小偷偷的最多钱数,那么他有两种状态,一种是偷了这个节点,另一种是没有偷这个节点。
以根节点为参照(可以参照下图来理解):
如果偷了root,那么肯定不能偷左节点和右节点,只能偷下面的节点;
如果没有偷root,那么可以偷左节点和右节点,也可以选择不偷,再偷下面的节点。
我们将其左子树和右子树看作一个整体,将两种状态的dp求出,那么到了最后,只要求两种dp的最大值就可以了。
具体代码如下:
/**
* 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) {
int[] result = dfs(root);
return Math.max(result[0], result[1]);
}
public int[] dfs(TreeNode root) {
if(root == null)
return new int[2];
int[] left = dfs(root.left);
int[] right = dfs(root.right);
int[] dp = new int[2];
dp[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
dp[1] = root.val + left[0] + right[0];
return dp;
}
}