




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).
1using System;
2using System.Collections.Generic;
3
4public class TreeNode {
5    public int val;
6    public TreeNode left, right;
7    public TreeNode(int x) { val = x; }
8}
9
10public class Solution {
11    public int MinDepth(TreeNode root) {
12        if (root == null) return 0;
13        Queue<(TreeNode, int)> queue = new Queue<(TreeNode, int)>();
14        queue.Enqueue((root, 1));
15
16        while (queue.Count > 0) {
17            var (node, depth) = queue.Dequeue();
18            if (node.left == null && node.right == null) return depth;
19            if (node.left != null) queue.Enqueue((node.left, depth + 1));
20            if (node.right != null) queue.Enqueue((node.right, depth + 1));
21        }
22        return 0;
23    }
24}
25This C# solution defines the BFS using a Queue of tuples, efficiently tracking each node and its depth. Leaf nodes cause the early exit and return of the minimum depth, as expected with BFS.
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.
1using namespace std;
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int minDepth(TreeNode* root) {
    if (root == nullptr) return 0;
    if (!root->left && !root->right) return 1;
    int left = root->left ? minDepth(root->left) : INT_MAX;
    int right = root->right ? minDepth(root->right) : INT_MAX;
    return 1 + min(left, right);
}
This C++ solution recurses through each node's children until a leaf is reached, at which point it returns the path's length. The algorithm compares the depth of the left and right sub-trees at each node, selecting the lesser depth.