-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbst1.cpp
More file actions
130 lines (120 loc) · 2.84 KB
/
bst1.cpp
File metadata and controls
130 lines (120 loc) · 2.84 KB
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
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node* pptr;
node* lch;
node* rch;
};
int del(int val, node* &root);
void in(node* root){
if(root != NULL){
in(root->lch);
cout << root->data << " ";
in(root->rch);
}
}
int varis(node* &ptr){
node* temp;
if(ptr->lch == NULL){
temp = ptr->rch;
while(temp->lch != NULL) temp = temp->lch;
return del(temp->data,ptr);
}
else{
temp = ptr->lch;
while(temp->rch != NULL) temp = temp->rch;
return del(temp->data,ptr);
}
}
int del(int val, node* &root){
node* temp = root;
while(temp != NULL && temp->data != val){
if(val > temp->data) temp = temp->rch;
else if(val < temp->data) temp = temp->lch;
}
if(temp == NULL){
cout << "Number not found in the tree" << endl;
}
else if(temp->lch == NULL && temp->rch == NULL){
if(temp == root){
root = NULL;
}
else if(temp->pptr->data > temp->data){
temp->pptr->lch = NULL;
}
else if(temp->pptr->data < temp->data){
temp->pptr->rch = NULL;
}
}
else{
int v = varis(temp);
temp->data = v;
}
return val;
}
void insert(node* &root, int data){
if(root == NULL){
node *temp = new node();
temp->data = data;
temp->lch = NULL;
temp->rch = NULL;
temp->pptr = NULL;
root = temp;
}
else if(data > root->data){
if(root->rch == NULL){
node *temp = new node();
temp->data = data;
temp->lch = NULL;
temp->rch = NULL;
temp->pptr = root;
root->rch = temp;
}
else{
insert(root->rch, data);
}
}
else if(data < root->data){
if(root->lch == NULL){
node *temp = new node();
temp->data = data;
temp->lch = NULL;
temp->rch = NULL;
temp->pptr = root;
root->lch = temp;
}
else{
insert(root->lch, data);
}
}
}
int main(){
node* root = NULL;
int n;
cout << "Enter number of elements" << endl;
cin >> n;
cout << "Enter elements" << endl;
for(int i = 0; i < n; i++){
int dtemp;
cin >> dtemp;
insert(root,dtemp);
}
cout << "Given elements are:" << endl;
in(root);
int flag = 1;
cout << endl;
while(flag){
cout << "Enter number to delete" << endl;
int num;
cin >> num;
del(num,root);
in(root);
if(root == NULL){
cout << "No more elements avilable" << endl;
break;
}
else cout << endl << "Do you want to delete more(1/0)" << endl;
cin >> flag;
}
}