leetcode题目:house robber iii

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int (TreeNode* root) {
if(!root)
return 0;
if(NULL == root->left && NULL == root->right)
return root->val;

int c1 = rob(root->left) + rob(root->right);
int c2 = root->val;
if(root->left)
c2 += rob(root->left->left) + rob(root->left->right);
if(root->right)
c2 += rob(root->right->left) + rob(root->right->right);
return c1 > c2 ? c1 : c2;
}
};