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.
Examples
Input: root = [1, 3, 2, 4]
Output: 2 Explanation: Minimum depth is between nodes 1 and 2 since minimum depth is defined as the number of nodes along the shortest path from the root node down to the nearest leaf node.
#include<iostream>usingnamespacestd;// Node structureclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// Function to find minimum depth using DFSintminDepth(Node*root){// Base case: if tree is emptyif(root==nullptr)return0;// If leaf node, depth is 1if(root->left==nullptr&&root->right==nullptr)return1;// Initialize depths as large valueintleft=INT_MAX,right=INT_MAX;// If left child exists, recur for left subtreeif(root->left!=nullptr)left=minDepth(root->left);// If right child exists, recur for right subtreeif(root->right!=nullptr)right=minDepth(root->right);// Return minimum of left and right subtree depths + 1 (for current node)return1+min(left,right);};intmain(){Node*root=newNode(12);root->left=newNode(8);root->right=newNode(18);root->left->left=newNode(5);root->left->right=newNode(11);cout<<minDepth(root);return0;}
C
#include<stdio.h>#include<stdlib.h>#include<limits.h>// Node structuretypedefstructNode{intdata;structNode*left;structNode*right;}Node;// Function to create a new nodeNode*createNode(intdata){Node*node=(Node*)malloc(sizeof(Node));node->data=data;node->left=NULL;node->right=NULL;returnnode;}// Function to find minimum depth using DFSintminDepth(Node*root){// Base case: if tree is emptyif(root==NULL)return0;// If leaf node, depth is 1if(root->left==NULL&&root->right==NULL)return1;// Initialize depths as large valueintleft=INT_MAX,right=INT_MAX;// If left child exists, recur for left subtreeif(root->left!=NULL)left=minDepth(root->left);// If right child exists, recur for right subtreeif(root->right!=NULL)right=minDepth(root->right);// Return minimum of left and right subtree depths + 1 (for current node)return1+(left<right?left:right);}intmain(){Node*root=createNode(12);root->left=createNode(8);root->right=createNode(18);root->left->left=createNode(5);root->left->right=createNode(11);printf("%d\n",minDepth(root));return0;}
Java
classNode{intdata;Nodeleft,right;publicNode(intitem){data=item;left=right=null;}}publicclassBinaryTree{Noderoot;// Function to find minimum depth using DFSintminDepth(Noderoot){if(root==null)return0;if(root.left==null&&root.right==null)return1;intleft=Integer.MAX_VALUE,right=Integer.MAX_VALUE;if(root.left!=null)left=minDepth(root.left);if(root.right!=null)right=minDepth(root.right);return1+Math.min(left,right);}publicstaticvoidmain(String[]args){BinaryTreetree=newBinaryTree();tree.root=newNode(12);tree.root.left=newNode(8);tree.root.right=newNode(18);tree.root.left.left=newNode(5);tree.root.left.right=newNode(11);System.out.println(tree.minDepth(tree.root));}}
Python
classNode:def__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to find minimum depth using DFSdefminDepth(root):ifrootisNone:return0ifroot.leftisNoneandroot.rightisNone:return1left=float('inf')right=float('inf')ifroot.leftisnotNone:left=minDepth(root.left)ifroot.rightisnotNone:right=minDepth(root.right)return1+min(left,right)# Main executionroot=Node(12)root.left=Node(8)root.right=Node(18)root.left.left=Node(5)root.left.right=Node(11)print(minDepth(root))
C#
usingSystem;// Node structurepublicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}// Function to find minimum depth using DFSpublicclassGfG{publicstaticintminDepth(Noderoot){// Base case: if tree is emptyif(root==null)return0;// If leaf node, depth is 1if(root.left==null&&root.right==null)return1;// Initialize depths as large valueintleft=Int32.MaxValue,right=Int32.MaxValue;// If left child exists, recur for left subtreeif(root.left!=null)left=minDepth(root.left);// If right child exists, recur for right subtreeif(root.right!=null)right=minDepth(root.right);// Return minimum of left and right subtree depths + 1 (for current node)return1+Math.Min(left,right);}publicstaticvoidMain(){Noderoot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);Console.WriteLine(minDepth(root));}}
JavaScript
classNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to find minimum depth using DFSfunctionminDepth(root){if(root===null)return0;if(root.left===null&&root.right===null)return1;letleft=Number.MAX_SAFE_INTEGER,right=Number.MAX_SAFE_INTEGER;if(root.left!==null)left=minDepth(root.left);if(root.right!==null)right=minDepth(root.right);return1+Math.min(left,right);}// Main executionletroot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);console.log(minDepth(root));
Output
2
Level Order Traversal - O(n) Time O(n) Space
The idea is to traverse the binary tree level by level using a queue. We start from the root node and process all nodes at the current level before moving to the next. A variable depth keeps track of the current level. As soon as we encounter the first leaf node, we return the current depth, because BFS guarantees that this is the minimum depth of the tree.
We begin with root and add it to the queue and initialize depth as 1.
At every level, we remove current level nodes (using queue size) and push nodes of next level.
We increment depth after every level
Whenever we encounter a leaf node, we return depth.
C++
#include<iostream>#include<queue>usingnamespacestd;// Node structureclassNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=nullptr;right=nullptr;}};// Function to find minimum depth using BFSintminDepth(Node*root){// Base case: if tree is emptyif(!root)return0;// Queue to store node along with its depthqueue<Node*>q;// Push root node with initial depth = 1q.push(root);intdepth=1;while(!q.empty()){intsz=q.size();for(inti=0;i<sz;i++){autonode=q.front();q.pop();// If current node is a leaf node, return its depth// (first leaf encountered in BFS gives minimum depth)if(!node->left&&!node->right)returndepth;// If left child exists, push it with depth + 1if(node->left)q.push(node->left);// If right child exists, push it with depth + 1if(node->right)q.push(node->right);}depth++;}returndepth;}intmain(){Node*root=newNode(12);root->left=newNode(8);root->right=newNode(18);root->left->left=newNode(5);root->left->right=newNode(11);cout<<minDepth(root);return0;}
C
#include<stdio.h>#include<stdlib.h>#include<stdbool.h>#include<stddef.h>// Node structuretypedefstructNode{intdata;structNode*left;structNode*right;}Node;Node*createNode(intval){Node*newNode=(Node*)malloc(sizeof(Node));newNode->data=val;newNode->left=NULL;newNode->right=NULL;returnnewNode;}typedefstructQueueNode{Node*node;structQueueNode*next;}QueueNode;typedefstructQueue{QueueNode*front;QueueNode*rear;}Queue;Queue*createQueue(){Queue*q=(Queue*)malloc(sizeof(Queue));q->front=q->rear=NULL;returnq;}voidenqueue(Queue*q,Node*node){QueueNode*newNode=(QueueNode*)malloc(sizeof(QueueNode));newNode->node=node;newNode->next=NULL;if(q->rear==NULL){q->front=q->rear=newNode;return;}q->rear->next=newNode;q->rear=newNode;}Node*dequeue(Queue*q){if(q->front==NULL)returnNULL;QueueNode*temp=q->front;Node*node=temp->node;q->front=q->front->next;if(q->front==NULL)q->rear=NULL;free(temp);returnnode;}// Function to find minimum depth using BFSintminDepth(Node*root){// Base case: if tree is emptyif(!root)return0;// Queue to store node along with its depthQueue*q=createQueue();// Push root node with initial depth = 1enqueue(q,root);intdepth=1;while(q->front!=NULL){intsz=0;QueueNode*temp=q->front;while(temp!=NULL){sz++;temp=temp->next;}for(inti=0;i<sz;i++){Node*node=dequeue(q);// If current node is a leaf node, return its depth// (first leaf encountered in BFS gives minimum depth)if(!node->left&&!node->right)returndepth;// If left child exists, push it with depth + 1if(node->left)enqueue(q,node->left);// If right child exists, push it with depth + 1if(node->right)enqueue(q,node->right);}depth++;}returndepth;}intmain(){Node*root=createNode(12);root->left=createNode(8);root->right=createNode(18);root->left->left=createNode(5);root->left->right=createNode(11);printf("%d\n",minDepth(root));return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;// Node structureclassNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=null;right=null;}}publicclassGfG{// Function to find minimum depth using BFSstaticintminDepth(Noderoot){// Base case: if tree is emptyif(root==null)return0;// Queue to store node along with its depthQueue<Node>q=newLinkedList<>();// Push root node with initial depth = 1q.add(root);intdepth=1;while(!q.isEmpty()){intsz=q.size();for(inti=0;i<sz;i++){Nodenode=q.poll();// If current node is a leaf node, return its depth// (first leaf encountered in BFS gives minimum depth)if(node.left==null&&node.right==null)returndepth;// If left child exists, push it with depth + 1if(node.left!=null)q.add(node.left);// If right child exists, push it with depth + 1if(node.right!=null)q.add(node.right);}depth++;}returndepth;}publicstaticvoidmain(String[]args){Noderoot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);System.out.println(minDepth(root));}}
Python
fromcollectionsimportdeque# Node structureclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Function to find minimum depth using BFSdefminDepth(root):# Base case: if tree is emptyifnotroot:return0# Queue to store node along with its depthq=deque([(root,1)])whileq:node,depth=q.popleft()# If current node is a leaf node, return its depth# (first leaf encountered in BFS gives minimum depth)ifnotnode.leftandnotnode.right:returndepth# If left child exists, push it with depth + 1ifnode.left:q.append((node.left,depth+1))# If right child exists, push it with depth + 1ifnode.right:q.append((node.right,depth+1))returndepthif__name__=='__main__':root=Node(12)root.left=Node(8)root.right=Node(18)root.left.left=Node(5)root.left.right=Node(11)print(minDepth(root))
C#
usingSystem;usingSystem.Collections.Generic;// Node structurepublicclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=null;right=null;}}publicclassGfG{publicstaticintminDepth(Noderoot){// Base case: if tree is emptyif(root==null)return0;// Queue to store node along with its depthQueue<Node>q=newQueue<Node>();// Push root node with initial depth = 1q.Enqueue(root);intdepth=1;while(q.Count>0){intsz=q.Count;for(inti=0;i<sz;i++){Nodenode=q.Dequeue();// If current node is a leaf node, return its depth// (first leaf encountered in BFS gives minimum depth)if(node.left==null&&node.right==null)returndepth;// If left child exists, push it with depth + 1if(node.left!=null)q.Enqueue(node.left);// If right child exists, push it with depth + 1if(node.right!=null)q.Enqueue(node.right);}depth++;}returndepth;}publicstaticvoidMain(){Noderoot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);Console.WriteLine(minDepth(root));}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Function to find minimum depth using BFSfunctionminDepth(root){// Base case: if tree is emptyif(!root)return0;// Queue to store node along with its depthletq=[];// Push root node with initial depth = 1q.push({node:root,depth:1});while(q.length>0){let{node,depth}=q.shift();// If current node is a leaf node, return its depth// (first leaf encountered in BFS gives minimum depth)if(!node.left&&!node.right)returndepth;// If left child exists, push it with depth + 1if(node.left)q.push({node:node.left,depth:depth+1});// If right child exists, push it with depth + 1if(node.right)q.push({node:node.right,depth:depth+1});}returndepth;}letroot=newNode(12);root.left=newNode(8);root.right=newNode(18);root.left.left=newNode(5);root.left.right=newNode(11);console.log(minDepth(root));