Very simple easy to understand solution with explaination


  • 0
    W
        private int sum = 0;
        public int sumOfLeftLeaves(TreeNode root) {
            return sumOfLeftLeaves(root, false);
        }
        
        public int sumOfLeftLeaves(TreeNode root, Boolean isLeft) {
            if (root == null) {
                return 0;
            }
            
            // checking both children determine if it is a leaf or not
            if (isLeft && root.left == null && root.right == null) { 
                sum += root.val;
            }
            
            // recursively call same function on left and right children
            TreeNode left = root.left, right = root.right;
            sumOfLeftLeaves(left, true); 
            sumOfLeftLeaves(right, false);
            return sum;
        }
    

Log in to reply
 

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