-
Notifications
You must be signed in to change notification settings - Fork 0
/
DepthBinaryTree.C
55 lines (47 loc) · 1.29 KB
/
DepthBinaryTree.C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// C++ program to find minimum depth of a given Binary Tree
#include <iostream> // std::cout
#include <algorithm> // std::min
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;
// If left subtree is NULL, recur for right subtree
if (!root->left)
return minDepth(root->right) + 1;
// If right subtree is NULL, recur for right subtree
if (!root->right)
return minDepth(root->left) + 1;
return min(minDepth(root->left), minDepth(root->right)) + 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 << minDepth(root);
return 0;
}