码迷,mamicode.com
首页 > 其他好文 > 详细

337. House Robber III

时间:2019-01-13 14:27:15      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:amp   each   ali   term   ever   alert   zed   only   NPU   

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:

Input: [3,2,3,null,3,null,1]

     3
    /    2   3
    \   \ 
     3   1

Output: 7 
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

Input: [3,4,5,1,3,null,1]

     3
    /    4   5
  / \   \ 
 1   3   1

Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

如果两间直接相连的房子在同一个晚上被闯入,它将自动报警。
确定小偷今晚可以在不报警的情况下抢劫的最大金额。


C++(8ms):
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int rob(TreeNode* root, int& l , int& r) {
13         if (root == NULL)
14             return 0 ;
15         int ll = 0 ,lr = 0 , rl = 0 , rr = 0 ;
16         l = rob(root->left,ll,lr) ;
17         r = rob(root->right,rl,rr) ;
18         return max(root->val + ll + lr + rl +rr , l+r) ;
19     }
20     
21     int rob(TreeNode* root) {
22         int l ,r ;
23         return rob(root,l,r) ;
24     }
25 };

 


C++(1184ms):
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int rob(TreeNode* root) {
13         if (root == NULL)
14             return 0 ;
15         int val1 = root->val ;
16         if (root->left != NULL)
17             val1 += rob(root->left->left) + rob(root->left->right) ;
18         if (root->right != NULL)
19             val1 += rob(root->right->left) + rob(root->right->right) ;
20         int val2 = rob(root->left) + rob(root->right) ;
21         return max(val1,val2) ;
22     }
23 };

 

337. House Robber III

标签:amp   each   ali   term   ever   alert   zed   only   NPU   

原文地址:https://www.cnblogs.com/mengchunchen/p/10262379.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!