后序遍历
状态定义
- 每个结点都保存一个
dp数组,记录选择偷和不偷,以及底下孩子结点积累的赃款。 dp[0]表示不偷当前结点,dp[1]表示偷当前结点。
状态转移
- 不偷当前结点。当前最大赃款等于左孩子偷和不偷中的最大赃款,加上右孩子偷和不偷中的最大赃款。
- 偷当前结点。两个孩子结点都不能偷。
class Solution {
public int rob(TreeNode root) {
int[] res = dfs(root);
return Math.max(res[0], res[1]);
}
public int[] dfs(TreeNode root) {
if (root == null) {
return new int[] { 0, 0 };
}
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;
}
}