111. Minimum Depth of Binary Tree
You are given the root of a binary tree; each node carries an integer val plus left and right child pointers, and an empty tree is a null root. Return the tree's minimum depth — the number of nodes on the shortest path that starts at the root and walks downward to a leaf, a node with no children.
The subtle case is a node with exactly one child: it is not a leaf, so a path can never end there — it has to continue into the child that exists. For an empty tree, return 0.
Your function receives the root node (or None/null) and returns a single integer.
Example 1:
Input: root = [3, 9, 20, null, null, 15, 7]
Output: 2
Explanation: The leaf 9 is reached after just two nodes (3 → 9); any path through 20 needs three.
Example 2:
Input: root = [2, null, 3, null, 4, null, 5, null, 6]
Output: 5
Explanation: Every node has only a right child, so the lone leaf is 6 and the only root-to-leaf path holds five nodes. The answer is not 1 — node 2 has a child, so it is not a leaf.
Constraints:
- 0 ≤ number of nodes ≤ 10⁴
- -1000 ≤ Node.val ≤ 1000
Hints:
Think recursively: a leaf contributes depth 1, and an internal node builds its answer from its children's answers. What goes wrong if you blindly take min(left, right)?
A missing child would report depth 0 and win the min, letting a path 'end' where no leaf exists. Guard the one-child case — or sweep breadth-first and return the level of the first leaf you dequeue.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: root = [3, 9, 20, null, null, 15, 7]
Expected output: 2