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


  • 22
    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;
        }
    

  • 1
    I

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


  • 1
    K

    nice default argument


  • 0

    @mzchen you did not follow the contract. if so, i would like to rewrite the definition of class TreeNode


  • 0

    @Castor_Xu The signature is more generalized and still compatible with the contract.


Log in to reply
 

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