forked from ambujraj/hacktoberfest2018
-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_search_tree.cpp
148 lines (136 loc) · 3.29 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#include<iostream>
#include<string>
using namespace std;
template <class t>
struct node
{
t val;
node<t>* l;
node<t>* r;
};
template<class t>
class bst
{
private:
void search_pos(node<t>* temp,node<t>* root)
{
if ((temp->val > root->val) && (root->r != NULL))
search_pos(temp,root->r);
if ((temp->val > root->val) && (root->r == NULL))
root->r = temp;
if ((temp->val < root->val) && (root->l != NULL))
search_pos(temp,root->l);
if ((temp->val < root->val) && (root->l == NULL))
root->l = temp;
}
public:
node<t>* root=NULL;
void insertnode()
{
node<t>* temp =new node<t>;
t n;
cin>>n;
temp->val= n;
temp->l = temp->r = NULL;
if (root == NULL)
root = temp;
else
search_pos(temp , root);
}
void inorder(node<t>*root)
{
if(root!=NULL)
{
inorder(root->l);
t n = root->val;
cout<<"\t"<<n;
inorder(root->r);
}
}
void preorder(node<t>*root)
{
if(root!=NULL)
{
t n = root->val;
cout<<"\t"<<n;
preorder(root->l);
preorder(root->r);
}
}
void postorder(node<t>*root)
{
if(root!=NULL)
{
postorder(root->l);
postorder(root->r);
t n = root->val;
cout<<"\t"<<n;
}
}
};
int main()
{
int n;
cout<<"\n 1...Integer\n 2... Character\n 3...Double\n 4... String";
cout<<"\nEnter your choice:- ";
cin>>n;
switch(n)
{
case 1:
{
bst<int>obj;
do
{
cout<<"Enter value to be inserted:- ";
obj.insertnode();
cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- ";
cin >> n;
}while(n!=0);
obj.inorder(obj.root);
break;
}
case 2:
{
bst<char>obj;
do
{
cout<<"Enter value to be inserted:- ";
obj.insertnode();
cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- ";
cin >> n;
}while(n!=0);
obj.inorder(obj.root);
break;
}
case 3:
{
bst<float>obj;
do
{
cout<<"Enter value to be inserted:- ";
obj.insertnode();
cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- ";
cin >> n;
}while(n!=0);
obj.inorder(obj.root);
break;
}
case 4:
{
bst<string>obj;
do
{
cout<<"Enter value to be inserted:- ";
obj.insertnode();
cout<<"\nDo u want to insert more ?? if yes enter 1 else 0:- ";
cin >> n;
}while(n!=0);
obj.inorder(obj.root);
break;
}
default:
cout<<"\nWrong choice";
break;
}
return 0;
}