337.打家劫舍 III
2021-07-26 本文已影响0人
justonemoretry
image.png
解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rob(TreeNode root) {
int[] res = robTree(root);
return Math.max(res[0], res[1]);
}
/**
* 递归获取当前节点往下,取当前节点的最大值、不取当前节点的最大值
*/
public int[] robTree(TreeNode root) {
if (root == null) {
return new int[]{0, 0};
}
int[] left = robTree(root.left);
int[] right = robTree(root.right);
// 取当前节点,不能再取子节点,能得到的最大值
int val1 = root.val + left[0] + right[0];
// 不取当前节点,子节点取不取都行,得到的最大值
int val0 = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return new int[]{val0, val1};
}
}