123.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.

转化为求二叉树上不能连续两个父子都被选定的最大值和。

分别计算是否选中跟结点可获得的值,选较大的那个。可采用递归的思想做。

当选中根结点时,则分别计算其左右孩子的左右孩子;不选中根结点时则可以计算其左右孩子。

/**
	 * 转化为求二叉树上不能连续两个父子都被选定的最大值和。
	 * @date 20150510 
	 * @param root
	 * @return
	 */
	
	 public int rob(TreeNode root) {
	 
		 /*根结点为空*/
		 if(root == null){
			 return 0;
		 }
		 /*只有根结点一个值*/
		 if(root.left == null && root.right == null){
			 return root.val;
		 }
		 /*分别计算是否选中跟结点可获得的值,选较大的那个*/
		 int t1 = root.val;//选中根结点时则递归计算其左右孩子的左右孩子
		 if(root.left != null){
			 t1 +=  rob(root.left.left);
			 t1 +=  rob(root.left.right);
		 }
		 if(root.right != null){
			 t1 +=  rob(root.right.left);
			 t1 +=  rob(root.right.right);
		 }
		 
		 int t2 = 0;//不选跟结点,则递归计算其左右孩子
		 if(root.left != null){
			 t2 +=  rob(root.left);
		 }
		 if(root.right != null){
			 t2 +=  rob(root.right);
		 }
		 return t1>t2?t1:t2;
	 }
	
}


你可能感兴趣的:(123.House Robber III)