Minimum Depth of Binary Tree
Easy · tree bfs
You are given the root of a binary tree. Return its minimum depth: the number of nodes on the shortest path that starts at the root and ends at a leaf.
A leaf is a node with no children. A node with only one child is not a leaf, so a path cannot stop there. A tree with a single node has minimum depth 1, and an empty tree has minimum depth 0.
Examples
Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: 2
Node 9 is a leaf directly under the root, so the path 3 -> 9 has 2 nodes.
Example 2
Input: root = [2, null, 3, null, 4, null, 5, null, 6]
Output: 5
Every node has exactly one child until the last, so the only leaf is 6 and the path has all 5 nodes.
Example 3
Input: root = [1, 2, 3, 4]
Output: 2
Node 3 is a leaf at depth 2, which beats node 4 at depth 3.
Constraints
- The number of nodes is in the range [0, 1000].
- -1000 <= Node.val <= 1000