1. 程式人生 > >Leetcode 337. 打家劫舍 III

Leetcode 337. 打家劫舍 III

return pan turn public right roc proc root tree

/**
 * 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); } };

Leetcode 337. 打家劫舍 III