LeetCode 337.
Tags: LeetCode
package lc_337;
public class Solution {
public int rob(TreeNode root) {
// Time Exceeded
// return recur(root, 0, false);
int[] ans = recursion(root);
return Math.max(ans[0], ans[1]);
}
public int recur(TreeNode root, int value, boolean banned){
if (root == null) return 0;
if (banned) return value + recur(root.left, value, false) + recur(root.right, value, false);
int take = root.val, not_take = 0;
if (root.left != null){
take += recur(root.left, value, true);
not_take += recur(root.left, value, false);
}
if (root.right != null){
take += recur(root.right, value, true);
not_take += recur(root.right, value, false);
}
return Math.max(take, not_take);
}
public int[] recursion(TreeNode root){
if (root == null) return new int[2];
int[] r = recursion(root.right);
int[] l = recursion(root.left);
int[] v = new int[2];
v[0] = root.val + r[1] + l[1]; // take account of current root
v[1] = Math.max(r[0], r[1]) + Math.max(l[0], l[1]); // not take account of current root
return v;
}
}
Check out the description of this problem at LC 337.