- House Robber III
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 1:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
This one has to be recursive, cause you don't really know which is going to be picked during the process. RobValue(Root)=Max of
- RobValue(Root.left) + RobValue(Root.right)
- RobValue(Root.left without left child) + RobValue(Root.right without right child) + Root.val;
The trick of this question is to return a pair of value from recursive call, res[2], first value is the max rob value from the current node, and res[1] is the max rob value without rob current node.
/**
* 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) {
return rob_(root)[0];
}
private int[] rob_(TreeNode root){
int[] res = {0 /*max of rob current sub tree*/,
0 /* max of rob left child and right child*/};
if(root != null){
int[] left = rob_(root.left);
int[] right = rob_(root.right);
res[1] = left[0] + right[0];
res[0] = Math.max(res[1], left[1] + right[1] + root.val);
}
return res;
}
}