Sum of Left Leaves

Sum of Left Leaves

Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

LeetCode Problem - 404

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

class Solution {
    // Function to calculate the sum of left leaves in a binary tree
    public int sumOfLeftLeaves(TreeNode root) {
        // If the root is null, return 0
        if (root == null) {
            return 0;
        }
        // Initialize sum to store the sum of left leaves
        int sum = 0;
        // If the left child of the root exists and it is a leaf node, add its value to the sum
        if (root.left != null && root.left.left == null && root.left.right == null) {
            sum += root.left.val;
        }
        // Recursively calculate the sum of left leaves in the left and right subtrees
        sum += sumOfLeftLeaves(root.left);
        sum += sumOfLeftLeaves(root.right);
        // Return the total sum of left leaves
        return sum;
    }
}