- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathInsertionInABST.cpp
90 lines (81 loc) · 1.75 KB
/
InsertionInABST.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
#include<iostream>
#include<cstdlib>
usingnamespacestd;
structnode {
int data;
structnode *left, *right;
};
// Create a node
structnode *createnode(int item) {
structnode *temp = (structnode *)malloc(sizeof(structnode));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
voidinorder(structnode *root) {
if (root != NULL) {
inorder(root->left);
cout << root->data << "";
inorder(root->right);
}
}
intsearch(structnode *root, int key){
structnode *prev = NULL;
while(root!=NULL){
prev = root;
if(key==root->data){
printf("Cannot insert %d, already in BST", key);
return1;
}
elseif(key<root->data){
root = root->left;
}
else{
root = root->right;
}
}
return0;
}
structnode *insert(structnode *node, int key) {
if(search(node,key)==0){
if (node == NULL){
returncreatenode(key);
}
if (key < node->data){
node->left = insert(node->left, key);
}
else{
node->right = insert(node->right, key);
}
}
return node;
}
intmain() {
structnode *root = NULL;
int ch;
int x;
cout<<"Press 0 to exit else enter 1: ";
cin>>ch;
while(ch!=0)
{
cout<<"\n"<<"1.Insertion"<<"\n"<<"2.View"<<"\n";
cout<<"\n"<<"Enter choice :";
cin>>ch;
switch (ch)
{
case1:
cout<<"Enter the value you want to insert in binary search tree: ";
cin>>x;
root = insert(root, x);
break;
case2:
cout << "Inorder traversal: ";
inorder(root);
break;
default:
printf("\nINVALID CHOICE !!");
break;
}
}
return0;
}