-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
237 lines (199 loc) · 6.56 KB
/
main.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*Дано число N < 10 и последовательность целых чисел из [-2 31 ..2 31 ] длиной N.
Требуется построить бинарное дерево, заданное наивным порядком вставки.
Т.е., при добавлении очередного числа K в дерево с корнем root, если root→Key ≤ K, то
узел K добавляется в правое поддерево root; иначе в левое поддерево root.
Требования: Рекурсия запрещена. Решение должно поддерживать передачу функции
сравнения снаружи.
10
2
5
6
4
7
8
9
3
1
10
построенное дерево:
2
/ \
1 5
/ \
4 6
/ \
3 7
\
8
\
9
\
10
Вывод
1 2 3 4 5 6 7 8 9 10
*/
#include <iostream>
#include <stack>
#include <vector>
#include <queue>
template<class T>
struct DefaultComparator {
bool operator()(const T &left, const T &right) const {
return left < right;
}
};
template<class T>
struct DefaulEqual {
bool operator()(const T &l, const T &r) const {
return l == r;
}
};
template<class Key, class Comparator = DefaultComparator<Key>, class Equal = DefaulEqual<Key>>
class BinarySearchTree {
struct Node {
Key key;
Node *left;
Node *right;
Node() : key(0), left(nullptr), right(nullptr) {}
Node(const Key &key) : key(key), left(nullptr), right(nullptr) {}
};
public:
BinarySearchTree(Comparator comp = Comparator(), Equal equal = Equal()) : root(nullptr), comp(comp), equal(equal) {}
~BinarySearchTree() {
if(!root){
return;
}
std::queue<Node*> delete_q;
delete_q.push(root);
while(!delete_q.empty()){
Node* current_node = delete_q.front();
delete_q.pop();
if(current_node->left){
delete_q.push(current_node->left);
}
if(current_node->right){
delete_q.push(current_node->right);
}
delete current_node;
}
}
void Add(const Key &key) {
Node **current_node = &root;
while (*current_node != nullptr) {
if (comp(key, (*current_node)->key)) {
current_node = &(*current_node)->left;
} else {
current_node = &(*current_node)->right;
}
}
*current_node = new Node(key);
}
bool Has(const Key &key) {
Node* current_node = root;
while (current_node != nullptr && !equal(current_node->key, key)){
if (comp(key, current_node->key)) {
current_node = current_node->left;
} else {
current_node = current_node->right;
}
}
if(!current_node){ // если вышли из while по nullptr то нет элемента
return false;
}
return true;
}
void Delete(const Key &key) {
if(equal(root->key, key)){
delete root;
root = nullptr;
}
Node** current_node = &root;
while (*current_node != nullptr) {
if (comp(key, (*current_node)->key)) { // если элемент меньше то налево
current_node = &(*current_node)->left;
} else {
if(equal((*current_node)->key, key)){ // иначе либо нашли
break;
}
current_node = &(*current_node)->right; // либо направо
}
}
if(!*current_node){ //если не нашли элемент такой
return;
}
Node* new_node = nullptr;
if((*current_node)->left && (*current_node)->right){ // если есть обе ветки
Node** min_from_right = &(*current_node)->right;
while ((*min_from_right)->left) { // ищем имнимальный элемент справа, чтобы им заменить удаляемый
min_from_right = &(*min_from_right)->left;
}
new_node = *min_from_right;
*min_from_right = (*min_from_right)->right; // на место минимума справа цепляем его правую ветку(если есть)
new_node->right = (*current_node)->right; //подцепляем старые указатели к новой ноде
new_node->left = (*current_node)->left;
delete *current_node;
*current_node = new_node;
return;
}
if((*current_node)->left){
new_node = (*current_node)->left;
} else{
new_node = (*current_node)->right;
}
delete *current_node;
*current_node = new_node;
}
std::vector<Key> make_vect_in_order() {
std::stack<Node *> stack;
std::vector<Key> vector;
Node *current_node = root;
while (current_node != nullptr || !stack.empty()) {
while (current_node != nullptr) {
stack.push((current_node));
current_node = (current_node)->left;
}
auto top_node = stack.top();
stack.pop();
vector.push_back(top_node->key);
if ((top_node)->right) {
current_node = (top_node)->right;
}
}
return vector;
};
private:
Node *root;
Comparator comp;
Equal equal;
};
int main() {
BinarySearchTree<int> bst;
size_t n = 0;
int curr = 0;
std::cin >> n;
for (int i = 0; i < n; ++i) {
std::cin >> curr;
bst.Add(curr);
}
std::vector<int> result_vect = bst.make_vect_in_order();
for (int i = 0; i < n; ++i) {
std::cout << result_vect[i] << " ";
}
// проверка метода Has, работает :)
// for(int j = 0; j < 13; j++) {
// if (bst.Has(j)) {
// std::cout << std::endl << "has";
// } else {
// std::cout << std::endl << "has not";
// }
// }
// проверка метода Delete, работает :)
// for(int j = 5; j < 9; j++) {
// bst.Delete(j);
// }
// std::vector<int> result_vect_after_delete = bst.make_in_order_vect();
// for (int i = 0; i < n - 4; ++i) {
// std::cout << result_vect_after_delete[i] << " ";
// }
return 0;
}