Concise 9ms C++ Recursive Solution


  • 0
    B
    int rob(TreeNode* root) {
            pair<int,int> ans = dfs(root);
            return max(ans.first, ans.second);
        }
        pair<int,int> dfs(TreeNode *root) {
            if (!root) 
                return {0,0};
            pair<int,int> left = dfs(root->left), right = dfs(root->right),ans({0, 0});
            ans.first = max(left.first, left.second) + max(right.first, right.second);
            ans.second = left.first + right.first + root->val;
            return ans;
        }
    

Log in to reply
 

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