forked from wahyuhjr/OpenEmailGenerator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Binary_Search_Tree.cpp
96 lines (85 loc) · 1.78 KB
/
Binary_Search_Tree.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Binary Search tree Implementation with insertion,peorder traversal
// and height finding utilities
#include<bits/stdc++.h>
using namespace std;
// Structure for Node
struct node{
struct node * left=NULL;
struct node * right=NULL;
int key;
}
;
//Utility to create a node
struct node *createNode(int data)
{
struct node* temp=(struct node*)malloc(sizeof(struct node));
temp->key=data;
return temp;
}
// Utitilty to insert a node in BST
struct node *insertBST(struct node* root,int data )
{
if(root==NULL)
{
return createNode(data);
}
else
{
if(data<=root->key)
{
root->left=insertBST(root->left,data);
}
else
{
root->right=insertBST(root->right,data);
}
}
return root;
}
// Utility to find the height of the BST from root
int height(struct node *root)
{
if(root==NULL)
return -1;
else
{
int hleft=height(root->left);
int hright=height(root->right);
return max(hleft,hright)+1;
}
}
// Utility to get preorder traversal of the BST
void preorder(struct node* root)
{
if(root==NULL)
return ;
else
{
preorder(root->left);
cout<<root->key<<" ";
preorder(root->right);
return;
}
}
// Driver Function
int main()
{
char ch='y';
int x;
cout<<"Want to enter a node in BST(Y/y)=";
cin>>ch;
struct node *root=NULL;
while(ch=='y')
{
cin>>x;
root=insertBST(root,x);
cout<<endl;
cout<<"Want to enter anothe node?(Y/y)=";
cin>>ch;
}
int hght=height(root);
cout<<"\nHeight of the enterd BST="<<hght;
cout<<endl;
preorder(root);
return 0;
}