Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6] Output: 5
Constraints:
[0, 105]
.-1000 <= Node.val <= 1000
The problem asks to find the minimum depth of a binary tree. The minimum depth is the shortest distance from the root node to any leaf node. A leaf node is a node with no children.
We can solve this problem using two primary approaches: Depth-First Search (DFS) and Breadth-First Search (BFS).
This approach uses recursion to traverse the tree. The core idea is:
null
, the depth is 0.null
), the depth is 1.Time Complexity: O(N), where N is the number of nodes in the tree. In the worst case, we visit every node. Space Complexity: O(H), where H is the height of the tree. This is due to the recursive call stack. In the worst case (a skewed tree), H can be equal to N.
This approach uses a queue to perform a level-order traversal.
Time Complexity: O(N), where N is the number of nodes. We visit each node once. Space Complexity: O(W), where W is the maximum width of the tree. In the worst case (a complete binary tree), W can be proportional to N.
The provided code snippets demonstrate both approaches in several programming languages. The structure is consistent across all languages:
minDepth
) takes the root node of the binary tree as input.null
(or equivalent in the language), returning 0 if it is.deque
in Python, ArrayDeque
in Java, queue
in C++, etc.) to perform the level-order traversal.Note: The code examples use a standard TreeNode definition specific to LeetCode's structure. You may need to adapt this definition depending on your environment. The core logic remains the same. The choice between DFS and BFS depends on factors like memory constraints (BFS is often better for very wide trees) and coding style preference. In this particular problem, the performance difference is usually negligible unless dealing with extremely large trees.