Skip to main content

337 House Robber III

Leetcode

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called root.

Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night.

Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.

和前面两个强盗抢劫一样,使用动态规划。递归的时候返回取当前节点的最优结果和不取当前节点的最优结果。

class Solution {
public int rob(TreeNode root) {
if(root==null) return 0;
int[] left=dp(root.left);
int[] right=dp(root.right);
int children = left[1]+right[1];
int noChildren = root.val+left[0]+right[0];
return children>noChildren? children:noChildren;
}

private int[] dp(TreeNode root){

if(root==null) return new int[]{0,0};

int[] left=dp(root.left);
int[] right=dp(root.right);

int children = left[1]+right[1];
int noChildren = root.val+left[0]+right[0];
return new int[]{children, noChildren};
}
}