-
Notifications
You must be signed in to change notification settings - Fork 0
/
atyp_BinaryTree.h
138 lines (128 loc) · 2.75 KB
/
atyp_BinaryTree.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
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
#pragma once
#include <type_traits>
namespace atyp {
//template<typename T>
//class BinaryTree {
// class Node {
// Node* l;
// Node* r;
// T* data;
// };
//
// T add(const T& a, const T& b) const
// {
// return a + b;
// }
// template<typename T>
// typename std::enable_if_t<
// std::disjunction<std::is_integer_v<T>, std::is_real_v<T>>>
// T add(const int a_int_a, const int a_int_b) const
// {
// return a_int_a + a_int_b;
// }
// //void doSomething(T * v);
// //
// //template <std::vector<int>>
// //void doSomething(std::vector<int> * v)
//};
class BinaryTree{
class Node{
public:
Node* l = nullptr;
Node* r = nullptr;
Node* p = nullptr;
int v = 0;
Node(int value, Node* parent){
p = parent;
v = value;
}
~Node(){
delete l;
delete r;
}
bool empty(){
return (l == nullptr && r == nullptr);
}
void add(const int& value){
if(value < v){
if(l)l->add(value);
else l = new Node(value, this);
}
else{
if(r)r->add(value);
else r = new Node(value, this);
}
}
Node*& operator[] (const char side){
if(side == 'l')return l;
if(side == 'r')return r;
return p;
}
};
Node* root = nullptr;
char nt(char value, char val1, char val2){
if(value == val1)return val2;
return val1;
}
public:
BinaryTree(){}
~BinaryTree(){
delete root;
}
void push(int value) {
if (root)root->add(value);
else root = new Node(value, nullptr);
}
bool find(int value) {
Node* current = root;
while (current != nullptr) {
if (value == current->v)return true;
if (value < current->v) {
current = current->l;
}
else {
current = current->r;
}
}
return false;
}
void remove(int value) {
Node* current = root;
bool found = false;
while (current != nullptr) {
if (value == current->v) {
unsigned short children = (current->l ? (current->r ? 2 : 1) : (current->r ? 1 : 0));
Node* parent = current->p;
switch (children)
{
case 0:
(current->p->l == current ? current->p->l : current->p->r) = nullptr;
current->l = current->r = nullptr;
delete current;
return;
case 1:
(current->p->l == current ? current->p->l : current->p->r) = (current->l ? current->l : current->r);
current->l = current->r = nullptr;
delete current;
return;
case 2:
Node* pathNode = current->r;
while (pathNode->l != nullptr) {
pathNode = pathNode->l;
}
pathNode->p->l = pathNode->r;
current->v = pathNode->v;
pathNode->l = pathNode->r = nullptr;
delete pathNode;
return;
}
}
if (value < current->v)
current = current->l;
else
current = current->r;
}
return;
}
};
}