-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbst.cpp
133 lines (130 loc) · 2.39 KB
/
bst.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
#include<bits/stdc++.h>
using namespace std;
struct node {
int data;
struct node *left, *right;
};
struct node* bstinsert(struct node* root, int val) {
struct node* temp = (struct node*)malloc(sizeof(node));
temp->data = val;
temp->left = temp->right = NULL;
if(root == NULL) {
root = temp;
cout<<"\nInserted\n\n";
return root;
}
struct node* trav = root;
while(1) {
if(val < trav->data) {
if(trav->left) {
trav = trav->left;
}
else {
trav -> left = temp;
break;
}
}
else if (val > trav->data) {
if(trav->right) {
trav = trav->right;
}
else {
trav->right = temp;
break;
}
}
}
cout<<"\nInserted\n\n";
return root;
}
struct node* bstdelete(struct node* root, int val) {
struct node* temp = root, *parent;
while(temp->data != val) {
parent = temp;
if(val < temp->data) temp = temp->left;
else temp = temp->right;
}
if(temp == root) {
if(temp->left) {
struct node* tp = temp->left;
parent = temp;
while(tp->right != NULL) {
parent = tp;
tp = tp->right;
}
temp->data = tp->data;
free(tp);
if(parent == temp)
parent->left = NULL;
else parent->right = NULL;
}
else {
struct node* tp = temp->right;
cout<<"%";
parent = temp;
while(tp->left != NULL) {
parent = tp;
tp = tp->left;
}
temp->data = tp->data;
free(tp);
if(parent == temp)
parent->right = NULL;
else parent->left = NULL;
}
}
else if(!temp->left && !temp->right) {
free(temp);
temp = NULL;
}
else if(temp->left && temp->right) {
struct node* tp = temp->left;
while(tp->right != NULL) {
tp = tp->right;
}
temp->data = tp->data;
free(tp);
tp = NULL;
}
else {
if(parent -> left == temp) {
if(temp->left) parent->left = temp->left;
else parent->left = temp->right;
}
else {
if(temp->left) parent->right = temp->left;
else parent->right = temp->right;
}
}
return root;
}
void inOrder(struct node* root) {
if(root == NULL) return;
inOrder(root->left);
cout<<root->data<<" ";
inOrder(root->right);
}
int main() {
int choice;
struct node* root = NULL;
while(1) {
cout<<"1) Enter\n2) Delete\n3) Traverse\n";
cin>>choice;
int val;
switch(choice) {
case 1:
cout<<"Enter value\n";
cin>>val;
root = bstinsert(root, val);
break;
case 2:
cin>>val;
bstdelete(root, val);
break;
case 3:
inOrder(root);
cout<<endl<<endl;
break;
}
}
}