-
Notifications
You must be signed in to change notification settings - Fork 0
/
BTree.cpp
76 lines (60 loc) · 1.6 KB
/
BTree.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
#include "BTree.h"
BTree::~BTree() {
delete root;
}
void BTree::Add(int newKey) {
if(root == nullptr)
Add_FirstElement(newKey);
else if(root->keysNum == (2 * order - 1))
Add_ToFullRoot(newKey);
else
root->InsertToThisNotFullNode(newKey);
}
void BTree::Add_FirstElement(const int newKey) {
root = new BTreeNode(order, true);
root->keys[0] = newKey;
root->keysNum += 1;
}
void BTree::Add_ToFullRoot(const int newKey) {
BTreeNode* newRoot = new BTreeNode(order, false);
newRoot->children[0] = root;
newRoot->SplitChild(0, root);
int indexOfChildThatWillHaveNewKey = (newRoot->keys[0] < newKey) ? 1 : 0;
newRoot->children[indexOfChildThatWillHaveNewKey]->InsertToThisNotFullNode(newKey);
root = newRoot;
}
void BTree::Print() const {
root->Print();
std::cout << "\n";
}
void BTree::Search(const int key) const {
char sign = '+';
if(root->Contains(key) == nullptr)
sign = '-';
std::cout << key << ' ' << sign << '\n';
}
void BTree::Load() {
// zabranie z wejscia '\n' i znaku nawiasu rozpoczynajacego drzewo
getchar();
getchar();
root = new BTreeNode(order, true);
root->LoadNode();
}
void BTree::Save() const {
std::cout << order << '\n';
root->Save();
std::cout << '\n';
}
void BTree::Remove(const int removedKey) {
if(root == nullptr)
return;
root->Remove(removedKey);
if(root->keysNum > 0)
return;
BTreeNode* oldRootToRemove = root;
if(root->isLeaf)
root = nullptr;
else
root = root->children[0];
delete oldRootToRemove;
}