337. House Robbery III
answer
Use depth-first search, divided into two cases of using the root node and not using the root node, recursively search the left and right child nodes.
/**
* 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) {
int[] result = dfs(root);
return Math.max(result[0],result[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 select = root.val + left[0] + right[0];
int unselect = Math.max(left[0],left[1]) + Math.max(right[0],right[1]);
return new int[]{
unselect,select};
}
}