Problem 421501 · medium · Level 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

    8
   / \
  4  13
     / \
    12  6

Input:  root = build_tree([8, 4, 13, None, None, 12, 6])
Output: 2
7
 \
  1
   \
    8
     \
      3

Input:  root = build_tree([7, None, 1, None, 8, None, 3])
Output: 4
Explanation: the only leaf is 3, 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…