-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbstBranch.hpp
91 lines (83 loc) · 1.88 KB
/
bstBranch.hpp
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
#ifndef BSTBRANCH_HPP
#define BSTBRANCH_HPP
#include <new>
#include "baseBranch.hpp"
template <typename Type>
class bstBranch : public baseBranch<Type>
{
public:
bstBranch() : baseBranch<Type>::baseBranch() { }
bstBranch(Type e) : baseBranch<Type>::baseBranch(e) { }
bstBranch(const bstBranch &b) {
this->data = b.data;
this->right = b.right;
this->left = b.left;
}
void operator=(const bstBranch &b) {
this->data = b.data;
this->right = b.right;
this->left = b.left;
}
void operator=(const Type t) {
this->data = t;
}
void add(bstBranch<Type> **, Type);
void remove(bstBranch<Type> **, Type);
};
template <typename Type>
void bstBranch<Type>::add(bstBranch<Type> **root, Type e)
{
#ifdef TESTING
if (this != *root)
throw "Bad memory location";
#endif // TESTING
try
{
while (*root)
{
if ((*root)->data == e)
throw "Duplicate element found";
root = (bstBranch<Type> **)(e < (*root)->data ? &(*root)->left : &(*root)->right);
}
*root = new bstBranch<Type>(e);
}
catch (std::bad_alloc e)
{
throw "Memory cannot be allocated";
}
}
template <typename Type>
void bstBranch<Type>::remove(bstBranch<Type> **root, Type e)
{
#ifdef TESTING
if (this != *root)
throw "Bad memory location";
#endif // TESTING
while (*root)
{
if ((*root)->data == e)
{
bstBranch<Type> *z = *root;
if (z->isLeaf())
*root = NULL;
else if (z->isOnlyLeftLinked())
*root = (bstBranch<Type> *)z->left;
else if (z->isOnlyRightLinked())
*root = (bstBranch<Type> *)z->right;
else
{
root = (bstBranch<Type> **)&z->right;
while ((*root)->left)
root = (bstBranch<Type> **)&(*root)->left;
z->data = (*root)->data;
z = *root;
*root = (bstBranch<Type> *)(*root)->right;
}
delete z;
return;
}
root = (bstBranch<Type> **)(e < (*root)->data ? &(*root)->left : &(*root)->right);
}
throw "Element not found";
}
#endif // BSTBRANCH_HPP