333/670

333. Sum of Left Leaves

Easy

You are given the root of a binary tree. A left leaf is a node that has no children of its own and hangs off its parent's left side. Return the sum of the values of every left leaf in the tree, as a single integer.

Two things trip people up: the root is never a left leaf (it has no parent), and a left child that has children of its own doesn't count — only genuine leaves do. If the tree is empty or contains no left leaves, the answer is 0.

The tree arrives in level order, with null marking a missing child.

Example 1 — which leaves countOnly leaves reached through a left edge count: 9 (left child of 3) and 15 (left child of 20). 7 is a leaf but a right child, so it is skipped. Sum = 9 + 15 = 24.
39left leaf2015left leaf7right leafLRLR9 + 15 = 24

Example 1:

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

Output: 24

Explanation: 9 is a leaf and is the left child of 3. 15 is a leaf and is the left child of 20. 7 is a leaf too, but it hangs on the right. 9 + 15 = 24.

Example 2:

Input: root = [1]

Output: 0

Explanation: The only node is the root. It has no parent, so it can't be anyone's left child — there are no left leaves.

Constraints:

  • 0 ≤ number of nodes ≤ 10⁴
  • -1000 ≤ Node.val ≤ 1000

Hints:

Whether a node is a left leaf isn't something the node can see on its own — it depends on how its parent reached it. Carry that context down with you.

DFS with a boolean flag: when you step into node.left pass isLeft = true, into node.right pass false. When you land on a node with no children and the flag is true, add its value to the total.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

Expected output: 24