Leetcode题解

来源:互联网 发布:金字塔软件官网 编辑:程序博客网 时间:2024/06/07 16:32

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.

链接

树形DFS,用一个辅助函数记录左右子树的数字之和,每次取左右之中的较大值。最后比较根节点的情况,返回一个最大值。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int rob(TreeNode* root) {
if(root==NULL) return 0;
vector res=dfs(root);
return max(res[0],res[1])
}
vector dfs(TreeNode* root){
vector res(2,0);
if(root==NULL) return res;
vector lft=dfs(root->left);
vector rht=dfs(root->right);
res[0]=max(lft[0],lft[1])+max(rht[0],rht[1]);
res[1]=root->val+lft[0]+rht[0];
return res;
}
};
“`