Skip to content

Commit e58f138

Browse files
authored
Create MinimumDepthOfABinaryTree.cpp
1 parent 67b6af3 commit e58f138

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

Diff for: MinimumDepthOfABinaryTree.cpp

+89
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
// C++ program to find minimum depth of a given Binary Tree
2+
#include<bits/stdc++.h>
3+
using namespace std;
4+
5+
// A Binary Tree Node
6+
struct Node
7+
{
8+
int data;
9+
struct Node *left, *right;
10+
};
11+
12+
// A queue item (Stores pointer to node and an integer)
13+
struct qItem
14+
{
15+
Node *node;
16+
int depth;
17+
};
18+
19+
// Iterative method to find minimum depth of Binary Tree
20+
int minDepth(Node *root)
21+
{
22+
// Corner Case
23+
if (root == NULL)
24+
return 0;
25+
26+
// Create an empty queue for level order traversal
27+
queue<qItem> q;
28+
29+
// Enqueue Root and initialize depth as 1
30+
qItem qi = {root, 1};
31+
q.push(qi);
32+
33+
// Do level order traversal
34+
while (q.empty() == false)
35+
{
36+
// Remove the front queue item
37+
qi = q.front();
38+
q.pop();
39+
40+
// Get details of the remove item
41+
Node *node = qi.node;
42+
int depth = qi.depth;
43+
44+
// If this is the first leaf node seen so far
45+
// Then return its depth as answer
46+
if (node->left == NULL && node->right == NULL)
47+
return depth;
48+
49+
// If left subtree is not NULL, add it to queue
50+
if (node->left != NULL)
51+
{
52+
qi.node = node->left;
53+
qi.depth = depth + 1;
54+
q.push(qi);
55+
}
56+
57+
// If right subtree is not NULL, add it to queue
58+
if (node->right != NULL)
59+
{
60+
qi.node = node->right;
61+
qi.depth = depth+1;
62+
q.push(qi);
63+
}
64+
}
65+
return 0;
66+
}
67+
68+
// Utility function to create a new tree Node
69+
Node* newNode(int data)
70+
{
71+
Node *temp = new Node;
72+
temp->data = data;
73+
temp->left = temp->right = NULL;
74+
return temp;
75+
}
76+
77+
// Driver program to test above functions
78+
int main()
79+
{
80+
// Let us create binary tree shown in above diagram
81+
Node *root = newNode(1);
82+
root->left = newNode(2);
83+
root->right = newNode(3);
84+
root->left->left = newNode(4);
85+
root->left->right = newNode(5);
86+
87+
cout << minDepth(root);
88+
return 0;
89+
}

0 commit comments

Comments
 (0)