Problem 421501 · medium · Phase 04 Non-Linear Data Structures

Shortest Root-to-Leaf Depth

binary trees · breadth-first search · early exit

The minimum depth of a binary tree is the number of nodes on the shortest path from the root down to a leaf (a node with no children). Given the root, return that number, or 0 for an empty tree. Beware: a node with one missing child is not a leaf.

Examples

    3
   / \
  9  20
     / \
    15  7

Input:  root = build_tree([3, 9, 20, None, None, 15, 7])
Output: 2
2
 \
  3
   \
    4
     \
      5

Input:  root = build_tree([2, None, 3, None, 4, None, 5])
Output: 4
Explanation: the only leaf is 5, so the root's missing left child does not count.

Constraints

  • 0 <= number of nodes <= 2000
  • Target complexity: O(n) time.

Goals

  • Understand why the shortest path must end at a leaf, not at a missing child
  • Stop a BFS as soon as the first leaf is found
  • Return 0 for an empty tree
Starting Python…