-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathBST.cpp
129 lines (129 loc) · 1.96 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
#include<bits/stdc++.h>
#define ll long long
using namespace std;
struct node{
int value;
node *left;
node *right;
node (){
left = NULL;
right = NULL;
}
};
node *root = new node();
bool flag = true;
void insert(int val){
if (flag){
flag = false;
root->value = val;
return;
}
node *temp = root;
node *temp1 = new node();
while (temp != NULL){
temp1 = temp;
if (temp->value > val){
temp = temp->left;
}
else{
temp = temp->right;
}
}
if (temp1->value > val){
node *ins = new node();
ins->value = val;
temp1->left = ins;
}
else{
node *ins = new node();
ins->value = val;
temp1->right = ins;
}
}
void print(){
queue<node *>q;
q.push(root);
while (q.size() > 0){
node *temp = q.front();
cout << temp->value << endl;
q.pop();
if (temp->left){
q.push(temp->left);
}
if (temp->right){
q.push(temp->right);
}
}
}
bool search(int val){
node *temp = root;
while (temp){
if (temp->value > val){
temp = temp->left;
}
if (temp->value < val){
temp = temp->right;
}
if (temp->value == val){
return true;
}
}
return false;
}
void remove(int val){
node *temp = root;
node *temp1;
if (!search(val)){
return;
}
while (temp->value != val){
temp1 = temp;
if (temp->value > val){
temp = temp->left;
}
else{
temp = temp->right;
}
}
if (temp->right){
node *temp1 = temp->right;
while (temp1->left != NULL){
temp1 = temp1->left;
}
int v = temp1->value;
remove(temp1->value);
temp->value = v;
}
else if (temp->left){
node *temp1 = temp->left;
while (temp1->right != NULL){
temp1 = temp1->right;
}
int v = temp1->value;
remove(temp1->value);
temp->value = v;
}
else{
if (temp1->value > val){
temp1->left = NULL;
}
else{
temp1->right = NULL;
}
}
}
int main(){
int n,i,el;
cout << "Enter no of nodes you want ";
cin >> n;
for (i=0;i<n;i++){
cin >> el;
insert(el);
}
print();
remove(1);
print();
remove(2);
print();
return 0;
}