Find Minimum Depth of a Binary Tree
Last Updated :
23 Jul, 2025
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.
For example, minimum depth of below Binary Tree is 2.

Note that the path must end on a leaf node. For example, the minimum depth of below Binary Tree is also 2.
10
/
5
Method 1: The idea is to traverse the given Binary Tree. For every node, check if it is a leaf node. If yes, then return 1. If not leaf node then if the left subtree is NULL, then recur for the right subtree. And if the right subtree is NULL, then recur for the left subtree. If both left and right subtrees are not NULL, then take the minimum of two depths.
Below is implementation of the above idea.
C++
// C++ program to find minimum depth of a given Binary Tree
#include<bits/stdc++.h>
using namespace std;
// A BT Node
struct Node
{
int data;
struct Node* left, *right;
};
int minDepth(Node *root)
{
// Corner case. Should never be hit unless the code is
// called on root = NULL
if (root == NULL)
return 0;
// Base case : Leaf Node. This accounts for height = 1.
if (root->left == NULL && root->right == NULL)
return 1;
int l = INT_MAX, r = INT_MAX;
// If left subtree is not NULL, recur for left subtree
if (root->left)
l = minDepth(root->left);
// If right subtree is not NULL, recur for right subtree
if (root->right)
r = minDepth(root->right);
//height will be minimum of left and right height +1
return min(l , r) + 1;
}
// Utility function to create new Node
Node *newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return (temp);
}
// Driver program
int main()
{
// Let us construct the Tree shown in the above figure
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout <<"The minimum depth of binary tree is : "<< minDepth(root);
return 0;
}
C
// C program to find minimum depth of a given Binary Tree
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// A BT Node
typedef struct Node {
int data;
struct Node *left, *right;
} Node;
int min(int num1, int num2)
{
return (num1 > num2) ? num2 : num1;
}
int minDepth(Node* root)
{
// Corner case. Should never be hit unless the code is
// called on root = NULL
if (root == NULL)
return 0;
// Base case : Leaf Node. This accounts for height = 1.
if (root->left == NULL && root->right == NULL)
return 1;
int l = INT_MAX;
int r = INT_MIN;
// If left subtree is not NULL, recur for left subtree
if (root->left)
l = minDepth(root->left);
// If right subtree is not NULL, recur for right subtree
if (root->right)
r = minDepth(root->right);
// height will be minimum of left and right height +1
return min(l, r) + 1;
}
// Utility function to create new Node
Node* newNode(int data)
{
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = data;
temp->left = temp->right = NULL;
return (temp);
}
// Driver program
int main()
{
// Let us construct the Tree shown in the above figure
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("The minimum depth of binary tree is : %d",
minDepth(root));
return 0;
}
// This code is contributed by aditya kumar (adityakumar129)
Java
/* Java implementation to find minimum depth
of a given Binary tree */
/* Class containing left and right child of current
node and key value*/
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree
{
//Root of the Binary Tree
Node root;
int minimumDepth()
{
return minimumDepth(root);
}
/* Function to calculate the minimum depth of the tree */
int minimumDepth(Node root)
{
// Corner case. Should never be hit unless the code is
// called on root = NULL
if (root == null)
return 0;
// Base case : Leaf Node. This accounts for height = 1.
if (root.left == null && root.right == null)
return 1;
// If left subtree is NULL, recur for right subtree
if (root.left == null)
return minimumDepth(root.right) + 1;
// If right subtree is NULL, recur for left subtree
if (root.right == null)
return minimumDepth(root.left) + 1;
return Math.min(minimumDepth(root.left),
minimumDepth(root.right)) + 1;
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("The minimum depth of "+
"binary tree is : " + tree.minimumDepth());
}
}
Python3
# Python program to find minimum depth of a given Binary Tree
# Tree node
class Node:
def __init__(self , key):
self.data = key
self.left = None
self.right = None
def minDepth(root):
# Corner Case.Should never be hit unless the code is
# called on root = NULL
if root is None:
return 0
# Base Case : Leaf node.This accounts for height = 1
if root.left is None and root.right is None:
return 1
# If left subtree is Null, recur for right subtree
if root.left is None:
return minDepth(root.right)+1
# If right subtree is Null , recur for left subtree
if root.right is None:
return minDepth(root.left) +1
return min(minDepth(root.left), minDepth(root.right))+1
# Driver Program
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print (minDepth(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
using System;
/* C# implementation to find minimum depth
of a given Binary tree */
/* Class containing left and right child of current
node and key value*/
public class Node
{
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree
{
//Root of the Binary Tree
public Node root;
public virtual int minimumDepth()
{
return minimumDepth(root);
}
/* Function to calculate the minimum depth of the tree */
public virtual int minimumDepth(Node root)
{
// Corner case. Should never be hit unless the code is
// called on root = NULL
if (root == null)
{
return 0;
}
// Base case : Leaf Node. This accounts for height = 1.
if (root.left == null && root.right == null)
{
return 1;
}
// If left subtree is NULL, recur for right subtree
if (root.left == null)
{
return minimumDepth(root.right) + 1;
}
// If right subtree is NULL, recur for left subtree
if (root.right == null)
{
return minimumDepth(root.left) + 1;
}
return Math.Min(minimumDepth(root.left), minimumDepth(root.right)) + 1;
}
/* Driver program to test above functions */
public static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
Console.WriteLine("The minimum depth of binary tree is : " + tree.minimumDepth());
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
/* javascript implementation to find minimum depth
of a given Binary tree */
/* Class containing left and right child of current
node and key value*/
class Node {
constructor(item) {
this.data = item;
this.left = this.right = null;
}
}
// Root of the Binary Tree
let root;
function minimumDepth() {
return minimumDepth(root);
}
/* Function to calculate the minimum depth of the tree */
function minimumDepth( root) {
// Corner case. Should never be hit unless the code is
// called on root = NULL
if (root == null)
return 0;
// Base case : Leaf Node. This accounts for height = 1.
if (root.left == null && root.right == null)
return 1;
// If left subtree is NULL, recur for right subtree
if (root.left == null)
return minimumDepth(root.right) + 1;
// If right subtree is NULL, recur for left subtree
if (root.right == null)
return minimumDepth(root.left) + 1;
return Math.min(minimumDepth(root.left), minimumDepth(root.right)) + 1;
}
/* Driver program to test above functions */
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
document.write("The minimum depth of "
+ "binary tree is : " + minimumDepth(root));
// This code contributed by aashish1995
</script>
OutputThe minimum depth of binary tree is : 2
Time Complexity: O(n), as it traverses the tree only once.
Auxiliary Space: O(h), where h is the height of the tree, this space is due to the recursive call stack.
Method 2: The above method may end up with complete traversal of Binary Tree even when the topmost leaf is close to root. A Better Solution is to do Level Order Traversal. While doing traversal, returns depth of the first encountered leaf node.
Below is the implementation of this solution.
C++
// C++ program to find minimum depth of a given Binary Tree
#include <bits/stdc++.h>
using namespace std;
// A Binary Tree Node
struct Node {
int data;
struct Node *left, *right;
Node(int d = 0)
: data{ d }
{
}
};
// A queue item (Stores pointer to node and an integer)
struct qItem {
Node* node;
int depth;
};
// Iterative method to find minimum depth of Binary Tree
int minDepth(Node* root)
{
// Corner Case
if (root == NULL)
return 0;
// Create an empty queue for level order traversal
queue<qItem> q;
// Enqueue Root and initialize depth as 1
qItem qi = { root, 1 };
q.push(qi);
// Do level order traversal
while (q.empty() == false) {
// Remove the front queue item
qi = q.front();
q.pop();
// Get details of the remove item
Node* node = qi.node;
int depth = qi.depth;
// If this is the first leaf node seen so far
// Then return its depth as answer
if (node->left == NULL && node->right == NULL)
return depth;
// If left subtree is not NULL, add it to queue
if (node->left != NULL) {
qi.node = node->left;
qi.depth = depth + 1;
q.push(qi);
}
// If right subtree is not NULL, add it to queue
if (node->right != NULL) {
qi.node = node->right;
qi.depth = depth + 1;
q.push(qi);
}
}
return 0;
}
// Utility function to create a new tree Node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in above diagram
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right= new Node(5);
cout << minDepth(root);
return 0;
}
Java
// Java program to find minimum depth
// of a given Binary Tree
import java.util.*;
public class GFG
{
// A binary Tree node
static class Node
{
int data;
Node left, right;
}
// A queue item (Stores pointer to
// node and an integer)
static class qItem
{
Node node;
int depth;
public qItem(Node node, int depth)
{
this.node = node;
this.depth = depth;
}
}
// Iterative method to find
// minimum depth of Binary Tree
static int minDepth(Node root)
{
// Corner Case
if (root == null)
return 0;
// Create an empty queue for level order traversal
Queue<qItem> q = new LinkedList<>();
// Enqueue Root and initialize depth as 1
qItem qi = new qItem(root, 1);
q.add(qi);
// Do level order traversal
while (q.isEmpty() == false)
{
// Remove the front queue item
qi = q.peek();
q.remove();
// Get details of the remove item
Node node = qi.node;
int depth = qi.depth;
// If this is the first leaf node seen so far
// Then return its depth as answer
if (node.left == null && node.right == null)
return depth;
// If left subtree is not null,
// add it to queue
if (node.left != null)
{
qi.node = node.left;
qi.depth = depth + 1;
q.add(qi);
}
// If right subtree is not null,
// add it to queue
if (node.right != null)
{
qi.node = node.right;
qi.depth = depth + 1;
q.add(qi);
}
}
return 0;
}
// Utility function to create a new tree Node
static Node newNode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Driver Code
public static void main(String[] args)
{
// Let us create binary tree shown in above diagram
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
System.out.println(minDepth(root));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python program to find minimum depth of a given Binary Tree
# A Binary Tree node
class Node:
# Utility to create new node
def __init__(self , data):
self.data = data
self.left = None
self.right = None
def minDepth(root):
# Corner Case
if root is None:
return 0
# Create an empty queue for level order traversal
q = []
# Enqueue root and initialize depth as 1
q.append({'node': root , 'depth' : 1})
# Do level order traversal
while(len(q)>0):
# Remove the front queue item
queueItem = q.pop(0)
# Get details of the removed item
node = queueItem['node']
depth = queueItem['depth']
# If this is the first leaf node seen so far
# then return its depth as answer
if node.left is None and node.right is None:
return depth
# If left subtree is not None, add it to queue
if node.left is not None:
q.append({'node' : node.left , 'depth' : depth+1})
# if right subtree is not None, add it to queue
if node.right is not None:
q.append({'node': node.right , 'depth' : depth+1})
# Driver program to test above function
# Lets construct a binary tree shown in above diagram
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print (minDepth(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
// C# program to find minimum depth
// of a given Binary Tree
using System;
using System.Collections.Generic;
class GFG
{
// A binary Tree node
public class Node
{
public int data;
public Node left, right;
}
// A queue item (Stores pointer to
// node and an integer)
public class qItem
{
public Node node;
public int depth;
public qItem(Node node, int depth)
{
this.node = node;
this.depth = depth;
}
}
// Iterative method to find
// minimum depth of Binary Tree
static int minDepth(Node root)
{
// Corner Case
if (root == null)
return 0;
// Create an empty queue for
// level order traversal
Queue<qItem> q = new Queue<qItem>();
// Enqueue Root and initialize depth as 1
qItem qi = new qItem(root, 1);
q.Enqueue(qi);
// Do level order traversal
while (q.Count != 0)
{
// Remove the front queue item
qi = q.Peek();
q.Dequeue();
// Get details of the remove item
Node node = qi.node;
int depth = qi.depth;
// If this is the first leaf node
// seen so far.
// Then return its depth as answer
if (node.left == null &&
node.right == null)
return depth;
// If left subtree is not null,
// add it to queue
if (node.left != null)
{
qi.node = node.left;
qi.depth = depth + 1;
q.Enqueue(qi);
}
// If right subtree is not null,
// add it to queue
if (node.right != null)
{
qi.node = node.right;
qi.depth = depth + 1;
q.Enqueue(qi);
}
}
return 0;
}
// Utility function to create a new tree Node
static Node newNode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
// Driver Code
public static void Main(String[] args)
{
// Let us create binary tree
// shown in above diagram
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
Console.WriteLine(minDepth(root));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript program to find minimum depth
// of a given Binary Tree
class Node
{
// Utility function to create a new tree Node
constructor(data)
{
this.data = data;
this.left = this.right = null;
}
}
class qItem
{
constructor(node,depth)
{
this.node = node;
this.depth = depth;
}
}
function minDepth(root)
{
// Corner Case
if (root == null)
return 0;
// Create an empty queue for
// level order traversal
let q = [];
// Enqueue Root and initialize depth as 1
let qi = new qItem(root, 1);
q.push(qi);
// Do level order traversal
while (q.length != 0)
{
// Remove the front queue item
qi = q.shift();
// Get details of the remove item
let node = qi.node;
let depth = qi.depth;
// If this is the first leaf node seen so far
// Then return its depth as answer
if (node.left == null && node.right == null)
return depth;
// If left subtree is not null,
// add it to queue
if (node.left != null)
{
qi.node = node.left;
qi.depth = depth + 1;
q.push(qi);
}
// If right subtree is not null,
// add it to queue
if (node.right != null)
{
qi.node = node.right;
qi.depth = depth + 1;
q.push(qi);
}
}
return 0;
}
// Driver Code
// Let us create binary tree shown
// in above diagram
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
document.write(minDepth(root));
// This code is contributed by rag2127
</script>
Time Complexity: O(n), where n is the number of nodes in the given binary tree. This is due to the fact that we are visiting each node once.
Auxiliary Space: O(n), as we need to store the elements in a queue for level order traversal.
Find Minimum Depth of a Binary Tree
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem