337.打家劫舍Ⅲ
题解
使用深度优先搜索,分使用根节点和不使用根节点两种情况,递归搜索左右子节点。
/**
* 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};
}
}