/** * 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: struct returnData { int qu; int buqu; returnData(int _qu, int _buqu): qu(_qu), buqu(_buqu){} }; returnData process(TreeNode* root) { if(root==nullptr) { return returnData(0,0); } returnData left = process(root->left); returnData right = process(root->right); //父节点取的情况下 int qu = left.buqu + right.buqu + root->val; //父节点不取的情况下 int a = left.qu+right.qu; int b = left.qu+right.buqu; int c = left.buqu+right.qu; int d = left.buqu+right.buqu; int buqu = max(max(max(a,b),c),d); return returnData(qu, buqu); } int rob(TreeNode* root) { if(root==nullptr) return 0; returnData ret = process(root); return max(ret.qu, ret.buqu); } };
原文地址:https://www.cnblogs.com/randyniu/p/9537530.html
时间: 2024-10-09 10:50:18