-
Notifications
You must be signed in to change notification settings - Fork 0
/
BTree.cpp
97 lines (95 loc) · 1.78 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
using namespace std;
class BNode
{
private:
int degree;
public:
int keys[1] = {};
BNode *children[1] = {};
int GetLength()
{
int length = 0;
for (int i : keys)
{
if (i != -1)
{
length++;
}
}
return length;
}
bool IsLeaf()
{
for (BNode *node : children)
{
if (node != nullptr)
return false;
}
return true;
}
BNode *Search(int value)
{
int a = 0;
while (a < GetLength() && value > keys[a])
{
a++;
}
if (keys[a] == value)
return this;
if (IsLeaf())
return nullptr;
return children[a]->Search(value);
}
void Traverse()
{
int index;
for (index = 0; index < GetLength(); index++)
{
if (!IsLeaf())
{
children[index]->Traverse();
cout << endl
<< keys[index];
}
}
if (!IsLeaf())
children[index]->Traverse();
}
BNode(int degree)
{
this->degree = degree;
children[degree - 1];
keys[2 * degree - 1];
for (int i = 0; i < 2 * degree - 1; i++)
{
keys[i] = -1;
}
}
~BNode() {}
friend class BTree;
};
class BTree
{
private:
BNode *root = nullptr;
int degree;
public:
BTree(BNode *root)
{
degree = root->degree;
this->root = root;
}
~BTree() {}
void Traverse()
{
if (root)
{
root->Traverse();
}
}
BNode *Search(int value)
{
return root == nullptr ? nullptr : root->Search(value);
}
};