337. House Robber III
House Robber III
3
/ \ 3
/ \Solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int rob(TreeNode root) {
int[] result = helper(root);
return Math.max(result[0], result[1]);
}
private int[] helper(TreeNode node) {
if (node == null) {
int[] result = new int[2];
return result;
}
int[] left = helper(node.left);
int[] right = helper(node.right);
int[] result = new int[2];
result[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
result[1] = node.val + left[0] + right[0];
return result;
}
}Last updated