-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary search tree.cpp
128 lines (125 loc) · 2.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
#include<iostream>
#include<conio.h>
using namespace std;
struct tree{
int data;
struct tree *left,*right;
};
struct tree *root=NULL,*newnode,*temp;
void menu(){
cout<<"main menu"<<endl;
cout<<"1.create bst"<<endl;
cout<<"inorder traversal"<<endl;
cout<<"preorder traversal"<<endl;
cout<<"postorder traversal"<<endl;
}
void create(int item){
int flag;
newnode=new tree();
newnode->left=NULL;
newnode->right=NULL;
newnode->data=item;
if(root==NULL){
root=newnode;
}
else{
flag=1,temp=root;
while(flag!=0){
if(newnode->data<temp->data){
if(temp->left==NULL){
temp->left=newnode;
flag=0;
}
else{
temp=temp->left;
}
}
else{
if(temp->right==NULL){
temp->right=newnode;
flag=0;
}
else{
temp=temp->right;
}
}
}
}
}
void inorder(struct tree*root){
if(root!=NULL){
inorder(root->left);
cout<<root->data;
inorder(root->right);
}
}
void preorder(struct tree *root){
if(root!=NULL){
cout<<root->data;
preorder(root->left);
preorder(root->right);
}
}
void postorder(struct tree *root){
if(root!=NULL){
postorder(root->left);
postorder(root->right);
cout<<root->data;
}
}
int search(struct tree *root,int key){
struct tree*temp;
temp=root;
int flag=-1;
while(temp->left!=NULL || temp->right!=NULL){
if(temp->data=key){
flag=1;}
else if(temp->data>key){
temp=temp->left;}
else if(temp->data<key){
temp=temp->right;}
}
//return flag;
}
int main(){
int choice,item,key,status;
menu();
int flag=1;
while(flag!=0){
cout<<"enter your choice ";
cin>>choice;
switch(choice){
case 1:
cout<<"enter data to insert";
cin>>item;
create(item);
break;
case 2:
cout<<"inorder traversal";
inorder(root);
break;
case 3:
cout<<"preorder traversal";
preorder(root);
break;
case 4:
cout<<"post order traversal";
postorder(root);
break;
case 5:
cout<<"enter the key to search";
cin>>key;
status=search(root,key);
if(status=1)
cout<<"data is found";
else
cout<<"data not found";
break;
default:
cout<<"enter the correct choice ";
flag=0;
break;
}
}
getch();
}