




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).
1from collections import deque
2
3class TreeNode:
4    def __init__(self, val=0, left=None, right=None):
5        self.val = val
6        self.left = left
7        self.right = right
8
9class Solution:
10    def minDepth(self, root: TreeNode) -> int:
11        if not root:
12            return 0
13
14        queue = deque([(root, 1)])
15        while queue:
16            node, depth = queue.popleft()
17            if not node.left and not node.right:
18                return depth
19            if node.left:
20                queue.append((node.left, depth + 1))
21            if node.right:
22                queue.append((node.right, depth + 1))
23        return 0
24This Python solution implements BFS using a deque from the collections module, allowing efficient append and pop operations. The BFS processes each level in sequence, updating the depth. The loop breaks and returns the minimum depth when a leaf node is encountered.
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.
1
Adopting a recursive path-seeking strategy, this JavaScript solution minimizes depth calculation by relying on the simplicity of recursion to naturally discern tree structures and consequential depth variability.