Share my C++ solution


  • 0
    H
    /**
     * 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, int& n){
            if(!root) return 0;
            if(!root->left&&!root->right)return root->val;
            int l=0,r=0,nl=0,nr=0;
            if(root->left)l=Rob(root->left,nl);
            if(root->right)r=Rob(root->right,nr);
            n=l+r;
            return max(n,nl+nr+root->val);
            
        }
        int rob(TreeNode* root) {
            int n=0;
            return Rob(root,n);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.