Problem 443247 · easy · Phase 04 Non-Linear Data Structures

Sum of Left Leaves

binary trees · recursion · leaf nodes

Given the root of a binary tree, return the sum of all left leaves: leaves that are the left child of their parent. The root is never a left leaf, so a single-node tree gives 0.

Examples

    3
   / \
  9  20
     / \
    15  7

Input:  root = build_tree([3, 9, 20, None, None, 15, 7])
Output: 24
Explanation: 9 and 15 are left leaves (9 + 15 = 24); 7 is a right leaf.
Input:  root = build_tree([7])
Output: 0

Constraints

  • 0 <= number of nodes <= 2000
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n) time.

Goals

  • Distinguish a left child from a right child during traversal
  • Only count nodes that are both leaves and left children
  • Handle the root, which is nobody's left child
Starting Python…