-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbts.h
91 lines (82 loc) · 1.68 KB
/
bts.h
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
#ifndef BTS
#define BTS
#include <functional>
/*
* https://www.linux.org.ru/forum/development/11597146
*/
template<typename T, typename D>
struct NodeCRTP {
NodeCRTP() = default;
NodeCRTP(T&& data):
data(std::move(data)) {}
T data;
D *left{nullptr}, *right{nullptr};
virtual ~NodeCRTP() noexcept {
if (left)
delete left;
if (right)
delete right;
}
};
template<typename T>
struct BtsNode : NodeCRTP<T, BtsNode<T>> {
using NodeCRTP<T, BtsNode<T>>::NodeCRTP;
};
template<class T>
class Bts {
using Node = BtsNode<T>;
public:
explicit Bts() = default;
Bts(Bts&&) = delete;
Bts& operator=(Bts&&) = delete;
virtual ~Bts() {if (root)
delete root;
qDebug() << "bts deleted";}
virtual void add(T& data) {
inc();
add(data,root);}
virtual void add(T&& data) {
inc();
add(std::move(data),root);}
void traverse(auto c) const { traverse(c,root);}
auto size() {return _size;}
private:
void add(T& data, Node *&n) {
if (n == nullptr) {
n = new Node;
n->data = data;
} else if (n->data < data) {
data.deep();
add(data, n->left);
} else {
data.deep();
add(data, n->right);
}
}
void add(T&& data, Node *&n) {
if (n == nullptr) {
n = new Node{std::move(data)};
} else if (n->data < data) {
data.deep();
add(std::move(data), n->left);
} else {
data.deep();
add(std::move(data), n->right);
}
}
bool traverse(auto& c, Node* n) const {
if (!n)
return false;
if (
traverse(c, n->left) ||
c(n->data) ||
traverse(c, n->right))
return true;
return false;
}
Node *root{nullptr};
protected:
void inc() {_size++;}
std::size_t _size{0};
};
#endif // BTS