3 line recursive c++ solution, no need to explain


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

  • 0
    G

    I was actually looking for this answer :) . my code is on similar idea but a bit long :D :D

      public int sumOfLeftLeaves(TreeNode root) {
            if(root == null) return 0;
            ArrayList<Integer> res = new ArrayList<Integer>();
            helper(root, res, false);
            return getSum(res);
        }
        
        public void helper(TreeNode root, ArrayList<Integer> res, boolean isLeft){
            if(root.left == null && root.right == null && isLeft){
                res.add(root.val);
                return ;
            }
            
            if(root.left != null) helper(root.left, res, true );
            if(root.right != null) helper(root.right, res, false);
            return;
        }
        
        public int getSum(ArrayList<Integer> res){
            if(res.size() == 0) return 0;
            int sum = 0;
            for(int n : res){
                sum+=n;
            }
            return sum;
        }
    

  • 0
    I

    @mzchen - Try not changing the signature of the function in the question to make it more challenging.


  • 1
    K

    nice default argument


Log in to reply
 

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