Skip to content

404. Sum of Left Leaves

View on LeetCode

Approach: BFS; when a left child is a leaf, add its value.

Complexity: O(n) time, O(w) space

js
/**
 * 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 current = [root]
    let next = []
    let sum = 0
    while (current.length) {
        current.forEach(node => {
            if (node.left) {
                if (!node.left.left && !node.left.right) {
                    sum += node.left.val
                } else {
                    next.push(node.left)
                }
            }
            if (node.right) {
                next.push(node.right)
            }
        })
        current = next
        next = []
    }
    return sum
};