




Sponsored
Sponsored
The BFS approach utilizes a queue to perform a level-order traversal of the tree. Each node is dequeued and checked if it is a leaf node. The level count is incremented each time a complete level is processed. The algorithm stops as soon as a leaf node is found, and the current level is returned as the minimum depth.
Time complexity is O(N), where N is the number of nodes, because each node is processed once. Space complexity is O(N) due to the storage requirements of the queue in the worst case (a complete/filled tree).
The solution uses a queue for the BFS traversal of the tree. Each node, along with its depth, is enqueued as we traverse. When the first leaf node is encountered (a node without left and right children), the current depth is returned as the minimum depth of the tree.
In the DFS approach, we perform a pre-order traversal of the tree with recursive calls. The minimum depth is calculated by determining the shortest path from the root to any leaf node, where leaf nodes are identified as those without children.
Time complexity is O(N) as each node requires inspection to determine minimum depth. Space complexity can be O(N) in the case of skewed trees due to the recursive stack's depth, but typically O(log N) for balanced trees.
1class TreeNode:
2    def __init__(self, val=0, left=None, right=None):
3        self.val = val
4        self.left = left
5        self.right = right
6
7class Solution:
8    def minDepth(self, root: TreeNode) -> int:
9        if not root:
10            return 0
11        if not root.left:
12            return 1 + self.minDepth(root.right)
13        if not root.right:
14            return 1 + self.minDepth(root.left)
15        return 1 + min(self.minDepth(root.left), self.minDepth(root.right))
16The recursive Python solution explores the minimum depth by traversing each sub-tree, employing the function's call stack to differentiate paths and returning the shortest discovered path to a leaf.