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.
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
思路:从下面往上传递信息,每个node往上传的信息有两个,偷本身的最大值和不偷本身的最大值。注意root不偷的时候,左右两边分别可以偷或者不偷中取大的,因为两个分开了;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private class Node {
int inmax;
int notinmax;
public Node(int inmax, int notinmax) {
this.inmax = inmax;
this.notinmax = notinmax;
}
}
public int rob(TreeNode root) {
if(root == null) {
return 0;
}
int[] res = {0};
findMax(root, res);
return res[0];
}
private Node findMax(TreeNode root, int[] res) {
if(root == null) {
return new Node(0,0);
}
if(root.left == null && root.right == null) {
res[0] = root.val;
return new Node(root.val, 0);
}
Node leftnode = findMax(root.left, res);
Node rightnode = findMax(root.right, res);
int inmax = root.val + leftnode.notinmax + rightnode.notinmax;
// 注意root不偷的时候,左右两边分别可以偷或者不偷中取大的;因为两个分开了;
int notinmax = Math.max(leftnode.inmax, leftnode.notinmax)
+ Math.max(rightnode.inmax, rightnode.notinmax);
res[0] = Math.max(res[0], Math.max(inmax, notinmax));
return new Node(inmax, notinmax);
}
}
思路2: 用array来传参,代码更简洁;array[0] 代表偷,array[1] 代表不偷。
/**
* 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) {
if(root == null) {
return 0;
}
int[] res = findMax(root);
return Math.max(res[0], res[1]);
}
private int[] findMax(TreeNode root) {
if(root == null) {
return new int[2];
}
int[] left = findMax(root.left);
int[] right = findMax(root.right);
// res[0] 表示偷当前node,res[1] 表示不偷当前node
int[] res = new int[2];
// steal current node
res[0] = root.val + left[1] + right[1];
// not steal current node;
res[1] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
return res;
}
}