初始版本,会超时
/**
* 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) {
if (root == null) return 0;
return Math.max(max(root, 0), max(root, 1));
}
public int max(TreeNode root, int select) {
if (root == null) return 0;
int max = 0;
int l0 = max(root.left, 0), l1 = max(root.left, 1);
int r0 = max(root.right, 0), r1 = max(root.right, 1);
if (select == 0) { // 不选择根节点
max = Math.max(l0, l1) + Math.max(r0, r1);
} else if (select == 1) { // 选择根节点
max = root.val + l0 + r0;
}
return max;
}
}
改进后的版本,可AC
/**
* 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) {
if (root == null) return 0;
int[] ans = max(root);
return Math.max(ans[0], ans[1]);
}
public int[] max(TreeNode root) {
if (root == null) return new int[2];
int[] ans = new int[2];
int[] left = max(root.left);
int[] right = max(root.right);
// 不选择该节点时的最大值
ans[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
// 选择该节点时的最大值
ans[1] = root.val + left[0] + right[0];
return ans;
}
}
区别在于后者对于每个节点只进行一次的计算搜索,一并返回得到
①选择该节点
②不选择该节点
的最大值。