一、问题描述:
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 1Maximum amount of money the thief can rob = 3 + 3 + 1 = 7 .
Example 2:
3 / \ 4 5 / \ \ 1 3 1Maximum amount of money the thief can rob = 4 + 5 = 9 .
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
二、解决思路:
动态规划的思想:每一个节点都有取和不取两种情况,用一个int 的数组来记录这两种情况的结果:re[0] 不取,re[1]取。 如果不取的话,re[0]就是左右孩子节点最大值,如果取得话,就是root.val 加上不取左右孩子节点的情况。
三、代码:
package T01;
/**
* @author 作者 : xcy
* @version 创建时间:2017年1月13日 下午12:26:00
* 类说明
*/
public class t337 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// TreeNode root = new TreeNode(3);
// TreeNode r1 = new TreeNode(4);
// TreeNode r2 = new TreeNode(5);
// TreeNode r3 = new TreeNode(1);
// TreeNode r4 = new TreeNode(3);
// TreeNode r5 = new TreeNode(1);
// root.left = r1;
// root.right = r2;
// r1.left = r3;
// r1.right = r4;
// r2.right = r5;
TreeNode root = new TreeNode(3);
TreeNode r1 = new TreeNode(2);
TreeNode r2 = new TreeNode(3);
TreeNode r3 = new TreeNode(3);
TreeNode r4 = new TreeNode(1);
root.left = r1;
root.right = r2;
r1.right = r3;
r2.right = r4;
System.out.println(rob(root));
}
public static int rob(TreeNode root) {
int[] re = SubRob(root);
return Math.max(re[0], re[1]);
}
public static int[] SubRob(TreeNode root) {
if (root == null) {
return new int[2];
}
int[] left = SubRob(root.left);
int[] right = SubRob(root.right);
int[] re = new int[2];
// re[0] not rob the root:
re[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
// re[1] rob the root;
re[1] = root.val + left[0] + right[0];
return re;
}
}