[leetcode]337. House Robber III
阿新 • • 發佈:2018-11-09
[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;
}
};