-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathBST_operations.cpp
145 lines (113 loc) · 3.08 KB
/
BST_operations.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
#include<iostream>
using namespace std;
class node{
public:
int data;
node *left, *right;
node(int data){
this->data = data;
left = NULL;
right = NULL;
}
};
node* insertBST(node* root, int val){
if(root == NULL)
return new node(val);
if(val<root->data)
root->left = insertBST(root->left, val);
else
root->right = insertBST(root->right, val);
return root;
}
void inorder(node* root){
if(root == NULL) return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
node* searchInBST(node* root, int key){
if(root == NULL) return NULL;
if(root->data == key) return root;
// data>key
if(root->data > key) return searchInBST(root->left, key);
//data<key
return searchInBST(root->right, key);
}
node* inorderSucc(node* root){
node* curr = root;
while(curr && curr->left != NULL)
curr = curr->left;
return curr;
}
node* deleteInBST(node* root, int val){
if(val < root->data)
root->left = deleteInBST(root->left, val);
else if(val > root->data)
root->right = deleteInBST(root->right, val);
else{
if(root->left == NULL){
node* temp = root->right;
free(root);
return temp;
}
else if(root->right == NULL){
node* temp = root->left;
free(root);
return temp;
}
//case 3
node* temp = inorderSucc(root->right);
root->data = temp->data;
root->right = deleteInBST(root->right, temp->data);
}
return root;
}
int main(){
node *root = NULL;
/*
4
/ \
2 5
/ \ \
1 3 7
*/
int option;
int data;
while(true){
cout<<"\n1. Create a Node 2. Insert 3. Display (In-order) 4. Search 5. Delete 0. Exit"<<endl;
cin>>option;
switch(option){
case 1:
cout<<"Enter the root data: ";
cin>>data;
root = insertBST(root, data);
break;
case 2:
cout<<"Enter the data: ";
cin>>data;
insertBST(root, data);
break;
case 3:
inorder(root);
cout<<endl;
break;
case 4:
cout<<"Enter the key: ";
cin>>data;
if(searchInBST(root, data) == NULL)
cout<<"Does not exists"<<endl;
else
cout<<"Exists"<<endl;
break;
case 5:
cout<<"Enter the value to be deleted: ";
cin>>data;
root = deleteInBST(root, data);
break;
}
if(option == 0){
break;
}
}
return 0;
}