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

Leaves Hanging on the Left

binary trees · recursion · leaf nodes

A gardener prunes only the leaves that hang off the left side of a branch. In a binary tree, such a left leaf is a node with no children that is the left child of its parent. Given the root, return the total of the values of all left leaves. The root has no parent, so it is never a left leaf, and a single-node tree gives 0.

Examples

      5
     / \
    3   8
   / \  /
  1  4 6

Input:  root = build_tree([5, 3, 8, 1, 4, 6])
Output: 7
Explanation: 1 and 6 are left leaves (1 + 6 = 7); 4 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…