leetcode 337. 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.

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public int rob(TreeNode root) {
12                 int robMoney=0;
13         if(root==null)
14         {
15             return 0;
16         }
17         robMoney=robsub(root);
18         return robMoney;
19     }
20         public int robsub(TreeNode root) {
21         int rob=0;
22         if(root==null)
23             return 0;
24         else if(root.left==null&&root.right==null)
25             return root.val;
26         else {
27             int robroot=0;
28             int robother=robsub(root.left)+robsub(root.right);
29             if(root.left==null)
30                 robroot=root.val+robsub(root.right.left)+robsub(root.right.right);
31             else if(root.right==null)
32                 robroot=root.val+robsub(root.left.left)+robsub(root.left.right);
33             else
34                 robroot=root.val+robsub(root.left.left)+robsub(root.left.right)+robsub(root.right.left)+robsub(root.right.right);
35             if(robroot>robother)
36                 rob=robroot;
37             else 
38                 rob=robother;
39         }
40         return rob;
41     }
42 }

 

转载于:https://www.cnblogs.com/HelloWorld-5/p/5421247.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值