DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

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.

Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumOfLeftLeaves = function(root) {
  let sum = 0;
  let isLeft = false;
  const getSum = (root, isLeft) => {
    if (root === null) {
      return;
    }

    if (root.right === null && root.left === null && isLeft) {
      if (isLeft) {
        sum = sum + root.val;
      }
    }
    getSum(root.left, true);
    getSum(root.right, false);
  };

  getSum(root, isLeft);
  return sum;
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)