1-liner C++ recursive solution


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

    Or the more readable 3-linear:

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

Log in to reply
 

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