-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary_search_tree.cpp
176 lines (157 loc) · 2.63 KB
/
binary_search_tree.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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/*
* Двоичное дерево поиска (binary search tree) с основным функционалом
* Зиновьев С.А., 21.07.2017
*/
#include<iostream>
using namespace std;
class BST
{
struct node
{
int data;
node* left;
node* right;
};
node* root;
node* make_empty(node* t)
{
if (t == NULL)
return NULL;
{
make_empty(t->left);
make_empty(t->right);
delete t;
}
return NULL;
}
node* insert(int x, node* t)
{
if (t == NULL)
{
t = new node;
t->data = x;
t->left = t->right = NULL;
}
else if (x < t->data)
t->left = insert(x, t->left);
else if (x > t->data)
t->right = insert(x, t->right);
return t;
}
node* find_min(node* t)
{
if (t == NULL)
return NULL;
else if (t->left == NULL)
return t;
else
return find_min(t->left);
}
node* find_max(node* t)
{
if (t == NULL)
return NULL;
else if (t->right == NULL)
return t;
else
return find_max(t->right);
}
node* remove(int x, node* t)
{
node* temp;
if (t == NULL)
return NULL;
else if (x < t->data)
t->left = remove(x, t->left);
else if (x > t->data)
t->right = remove(x, t->right);
else if (t->left && t->right)
{
temp = find_min(t->right);
t->data = temp->data;
t->right = remove(t->data, t->right);
}
else
{
temp = t;
if (t->left == NULL)
t = t->right;
else if (t->right == NULL)
t = t->left;
delete temp;
}
return t;
}
void inorder(node* t)
{
if (t == NULL)
return;
inorder(t->left);
cout << t->data << " ";
inorder(t->right);
}
void prefix(node* t)
{
if (t == NULL)
return;
cout << t->data << " ";
prefix(t->left);
prefix(t->right);
}
node* find(node* t, int x)
{
if (t == NULL)
return NULL;
else if (x < t->data)
return find(t->left, x);
else if (x > t->data)
return find(t->right, x);
else
return t;
}
public:
BST()
{
root = NULL;
}
~BST()
{
root = make_empty(root);
}
void insert(int x)
{
root = insert(x, root);
}
void remove(int x)
{
root = remove(x, root);
}
void display()
{
inorder(root);
//prefix(root);
cout << endl;
}
void search(int x)
{
root = find(root, x);
}
};
int main(int argc, char *argv[])
{
BST tree;
/*tree.insert(20);
tree.insert(25);
tree.insert(15);
tree.insert(10);
tree.insert(30);
tree.display();
tree.remove(20);
tree.display();
tree.remove(25);
tree.display();
tree.remove(30);
tree.display();*/
system("pause");
return EXIT_SUCCESS;
}