DEV Community

Karleb
Karleb

Posted on

404. Sum of Left Leaves

https://leetcode.com/problems/sum-of-left-leaves/description/?envType=daily-question&envId=2024-04-14


/**
 * 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

  const leftLeaf = node => !node.right && !node.left

  function dfs(node, isLeft) {
    if (!node) return

    if(isLeft && leftLeaf(node)) {
        sum += node.val
        return
    }

    dfs(node.right, false)
    dfs(node.left, true)
  }

  dfs(root, false)
  return sum
};



Enter fullscreen mode Exit fullscreen mode

Top comments (0)