Skip to problem
←

Sum of Left Leaves

Easy 0 attempts

You're given the root of a binary tree. A leaf is any node without children. A node counts as a left leaf only if it's a leaf and it's the left child of its parent. Add up the values of every left leaf in the tree and return the total — 0 if there aren't any.

The root has no parent and never counts as a left leaf, even when it is the only node. A left child with any children is not a leaf. Count qualifying leaves anywhere in the tree, including inside a right subtree; values may be negative.

Function contract

Implement sumOfLeftLeaves(root). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return the sum of values of leaves that are left children. The root itself never counts as a left leaf.

Example 1

Input
root = [3,9,20,null,null,15,7]
Output
24

Explanation: The left leaves are 9 and 15, so the sum is 24. The right leaf 7 does not count.

Example 2

Input
root = [1]
Output
0
Constraints
  • 1 <= number of nodes <= 1000
  • -1000 <= Node.val <= 1000

DFS

javascript
function sumOfLeftLeaves(root) {
  if (!root) return 0;
  let sum = 0;
  if (root.left && !root.left.left && !root.left.right) sum += root.left.val;
  else sum += sumOfLeftLeaves(root.left);
  sum += sumOfLeftLeaves(root.right);
  return sum;
}

Time: O(n) | Space: O(h)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript