Leetcode 337. House Robber III

337. House Robber III

  • Total Accepted: 18475
  • Total Submissions: 47725
  • Difficulty: Medium

 

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.

 

 

思路:基本思路和Leetcode 198. House Robber相同,只是将传递公式植入到二叉树的DFS过程中。

 

代码:

 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     void rob(TreeNode* root,int& pre,int& cur){
13         if(!root) return;
14         int lpre=0,lcur=0,rpre=0,rcur=0;
15         rob(root->left,lpre,lcur);
16         rob(root->right,rpre,rcur);
17         pre=lcur+rcur;
18         cur=max(lpre+rpre+root->val,pre);
19     }
20     int rob(TreeNode* root) {
21         int pre=0,cur=0;
22         rob(root,pre,cur);
23         return max(pre,cur);
24     }
25 };

 

posted @ 2016-07-26 19:17  Deribs4  阅读(130)  评论(0编辑  收藏  举报