C++ 2 lines


  • 0
    int sumOfLeftLeaves(TreeNode* root, bool isLeft = false) {
            if (!root || (!root->left && !root->right)) { return root && isLeft ? root->val : 0; }
            return sumOfLeftLeaves(root->left, true) + sumOfLeftLeaves(root->right, false);
    }
    

  • 3
    F

    This is not two lines, but you write it in two lines, you can even write it in only one line.


  • 0

    @fhqplzj
    Thanks for your comment.
    However I think the decomposition is clear:
    first line is the base case, and second line is non-base case.


  • 1

    I had the same solution in several more lines:

        int sumOfLeftLeaves(TreeNode* r) {
            return helper(r, false);
        }
        
        int helper(TreeNode* r, bool left) {
            if (!r) return 0;
            if (!r->left && !r->right) return left? r->val : 0;
            return helper(r->left, true) + helper(r->right, false);
        }
    

  • 0
    S

    @fhqplzj
    Hahahaha.
    Couldn't agree more


Log in to reply
 

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