C++代码
递归的思想去做,只能后序遍历,层序行不通。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<TreeNode*, int> umap;
int rob(TreeNode* root)
{
if (root == nullptr) return 0;
if (root->left == nullptr && root->right == nullptr) return root->val;
if (umap[root]) return umap[root];
//stole root
int val1 = root->val;
if (root->left) val1 += rob(root->left->left) + rob(root->left->right);
if (root->right) val1 += rob(root->right->left) + rob(root->right->right);
//not stole root
int val2 = rob(root->left) + rob(root->right);
umap[root] = max(val1, val2);
return max(val1, val2);
}
};
动态规划+递归 【都是时间O(n) 空间O(logn) 我觉得都最少是O(n) 下面的方法节省了哈希表的空间】我觉得还是上面那个简单
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int rob(TreeNode* root)
{
if (root == nullptr) return 0;
if (root->left == nullptr && root->right == nullptr) return root->val;
vector<int> ans = robTree(root);
return max(ans[0], ans[1]);
}
vector<int> robTree(TreeNode* cur)
{
//终止条件
if (cur == nullptr) return vector<int> {0, 0};
vector<int> left = robTree(cur->left);
vector<int> right = robTree(cur->right);
int val1 = cur->val + left[0] + right[0]; //stole cur node, 左右都不偷
int val2 = max(left[0], left[1]) + max(right[0], right[1]);//not stole cur node
return vector<int> {val2, val1};//注意这个别写反了
}
};
官方版
struct SubtreeStatus {
int selected;
int notSelected;
};
class Solution {
public:
SubtreeStatus dfs(TreeNode* node) {
if (!node) {
return {0, 0};
}
auto l = dfs(node->left);
auto r = dfs(node->right);
int selected = node->val + l.notSelected + r.notSelected;
int notSelected = max(l.selected, l.notSelected) + max(r.selected, r.notSelected);
return {selected, notSelected};
}
int rob(TreeNode* root) {
auto rootStatus = dfs(root);
return max(rootStatus.selected, rootStatus.notSelected);
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/house-robber-iii/solution/da-jia-jie-she-iii-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。