'lintcode 打劫房屋3'

@TOC

描述

在上次打劫完一条街道之后和一圈房屋之后,窃贼又发现了一个新的可以打劫的地方,但这次所有的房子组成的区域比较奇怪,聪明的窃贼考察地形之后,发现这次的地形是一颗二叉树。与前两次偷窃相似的是每个房子都存放着特定金额的钱。你面临的唯一约束条件是:相邻的房子装着相互联系的防盗系统,且当相邻的两个房子同一天被打劫时,该系统会自动报警。

算一算,如果今晚去打劫,你最多可以得到多少钱,当然在不触动报警装置的情况下。

样例

Example1

Input: {3,2,3,#,3,#,1}
Output: 7
Explanation:
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
3
/ \
2 3
\ \
3 1
Example2

Input: {3,4,5,1,3,#,1}
Output: 9
Explanation:
Maximum amount of money the thief can rob = 4 + 5 = 9.
3
/\ \
4 5
/ \ \
1 3 1

思路

对于每一个节点的最大得分只有两种情况,一个是拿这个节点的,一个是不拿这个节点的,用一个长度为2的数组来保存这两种情况的得分。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/

class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: The maximum amount of money you can rob tonight
*/
int houseRobber3(TreeNode * root) {
// write your code here
vector<int> res = rob(root);
return max(res[0], res[1]);

}

vector<int> rob(TreeNode *root) {
vector<int> res(2,0);
if (!root) return res;

vector<int> left = rob(root->left);
vector<int> right = rob(root->right);

res[0] = max(left[0],left[1]) + max(right[1],right[0]);
res[1] = root->val + left[0] + right[0];
}
};
-------------end of filethanks for reading-------------