[leetcode]337. House Robber III
Analysis
fighting!!!—— [每天刷题并不难0.0]
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.
递归解决,遍历二叉树的每个节点,第一种情况是包含该节点,不包含该节点的左节点和右节点;第二种情况是不包含该节点,则将以其左节点为根节点的子树得到的最大值加上以其右节点为根节点的子树得到的最大值。
Implement
/**
* 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) {
vector<int> res = DFS(root);
return max(res[0], res[1]);
}
vector<int> DFS(TreeNode* node){
vector<int> res(2, 0);
if(!node)
return res;
vector<int> left = DFS(node->left);
vector<int> right = DFS(node->right);
res[0] = max(left[0], left[1])+max(right[0], right[1]);
res[1] = left[0]+right[0]+node->val;
return res;
}
};