Binary Tree Left Leaves Sum: Algorithm and JavaScript Implementation

Problem:

Given a binary tree, calculate the sum of all left leaves.

Example:

Input:

+ 
1
/ \
2   3

Output: 6

Explanation:

Node 1's value is 1, and its two child nodes have values 2 and 3, so the total sum is 6.

Algorithm:

  1. Base Case: If the root is null, return 0.
  2. Left Leaf Check: If the current node has a left child, and the left child is a leaf node (has no children), add the left child's value to the sum.
  3. Recursive Traversal: Recursively call the function for the left and right subtrees.
  4. Return Sum: Return the total sum calculated.

JavaScript Implementation:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumOfLeftLeaves = function(root) {
    if(!root) return 0;
    let res = 0;
    if(root.left && !root.left.left && !root.left.right){
        res += root.left.val;
    }else{
        res += sumOfLeftLeaves(root.left);
    }
    res += sumOfLeftLeaves(root.right);
    return res;
};

This code uses recursion to traverse the tree and identifies left leaves based on the conditions root.left and !root.left.left && !root.left.right. It efficiently calculates the sum of all left leaves in the binary tree.

Binary Tree Left Leaves Sum: Algorithm and JavaScript Implementation