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:

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 };

 

posted @ 2019-01-13 13:22  __Meng  阅读(174)  评论(0编辑  收藏  举报