Clean Java solution


  • 0
    T
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            
            //Recurse if the root isn't null.
            if(root != null){
                return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false);
            }
            
            //If the root is null, the sum must be zero.
            return 0;
        }
        
        public int sumOfLeftLeaves(TreeNode n, boolean isLeft){
            if(n == null){
                return 0;
            }
            
            //If the left and right leaves are null, this is a leaf.
            if(n.left == null && n.right == null){
                
                //Left leaf, return its value
                if(isLeft){
                    return n.val;
                } 
                
                //Right leaf, return zero
                else{
                    return 0;
                }
            }
            
            //If not a leaf, recurse on children
            return sumOfLeftLeaves(n.left, true) + sumOfLeftLeaves(n.right, false);
        }
        
    }

Log in to reply
 

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