The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "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 forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example
分析:与上两道题不同,这道题无法使用DP解决。但是涉及到树的问题一般可以通过递归解决。将Root,Root.left和Root.right看作一组,针对每一组,有两种情况,
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Root,Root.left的孩子和Root.right孩子,或者root.left和root.right. 这里我们分别计算这两种情况并且取最大值即可
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param root: The root of binary tree.
* @return: The maximum amount of money you can rob tonight
*/
Map<TreeNode, Integer> res = new HashMap<TreeNode, Integer>();
public int houseRobber3(TreeNode root) {
if(root == null) return 0;
if(res.get(root) != null) return res.get(root);
int includeRoot = root.val;
if(root.left != null) {
includeRoot += houseRobber3(root.left.left);
includeRoot += houseRobber3(root.left.right);
}
if(root.right != null) {
includeRoot += houseRobber3(root.right.left);
includeRoot += houseRobber3(root.right.right);
}
int exceptRoot = houseRobber3(root.left) + houseRobber3(root.right);
int val = Math.max(includeRoot, exceptRoot);
res.put(root, val);
return val;
}
}