Java, clean, no helper, recursive


  • 7
    public class Solution {
        public int sumOfLeftLeaves(TreeNode n) {
            if(n==null ||(n.left==null && n.right ==null))return 0;
            int l=0,r=0;
            if(n.left!=null)l=(n.left.left==null && n.left.right==null)?n.left.val:sumOfLeftLeaves(n.left);
            if(n.right!=null)r=sumOfLeftLeaves(n.right);
            return l+r;
        }
    }
    

  • 1
    P

    Great solution.. Made it more simpler.. Checking n.right for null can be avoided..

        public int sumOfLeftLeaves(TreeNode n) {
            if(n==null ||(n.left==null && n.right ==null))  return 0;
            int l=0;
            if(n.left!=null)l=(n.left.left==null && n.left.right==null)?n.left.val:sumOfLeftLeaves(n.left);
            return l+sumOfLeftLeaves(n.right);
        }
    

  • 1
    S

    Simplified version:

        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null) return 0;
            int l = 0;
            if (root.left != null) l = root.left.left == null && root.left.right == null ? root.left.val : sumOfLeftLeaves(root.left);
            return l + sumOfLeftLeaves(root.right);
        }
    

  • 1
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null) return 0;
    
            if (root.left != null && (root.left.left == null && root.left.right == null)) {
                return sumOfLeftLeaves(root.right) + root.left.val;
            }
    
            return  sumOfLeftLeaves(root.right) + sumOfLeftLeaves(root.left);
        }
    }
    

Log in to reply
 

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