2023每日刷题(五十二)
Leetcode—337.打家劫舍III
算法思想
实现代码
/*** 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:pair<int, int> dfs(TreeNode* root) {if(root == nullptr) {return {0, 0};}auto [left_rob, left_not_rob] = dfs(root->left);auto [right_rob, right_not_rob] = dfs(root->right);// 选该结点int rob = left_not_rob + right_not_rob + root->val;// 不选该结点int not_rob = max(left_rob, left_not_rob) + max(right_rob, right_not_rob);return {rob, not_rob};}int rob(TreeNode* root) {auto [rob, not_rob] = dfs(root);return max(rob, not_rob);}
};
运行结果
之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!