-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathB Tree.py
More file actions
230 lines (186 loc) · 6.62 KB
/
B Tree.py
File metadata and controls
230 lines (186 loc) · 6.62 KB
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
class BTreeNode:
def __init__(self, t, is_leaf):
self.t = t
self.is_leaf = is_leaf
self.keys = []
self.children = []
def insert_non_full(self, key):
i = len(self.keys) - 1
if self.is_leaf:
while i >= 0 and key < self.keys[i]:
i -= 1
self.keys.insert(i + 1, key)
else:
while i >= 0 and key < self.keys[i]:
i -= 1
i += 1
if len(self.children[i].keys) == 2 * self.t - 1:
self.split_child(i)
if key > self.keys[i]:
i += 1
self.children[i].insert_non_full(key)
def split_child(self, i):
t = self.t
child = self.children[i]
new_child = BTreeNode(t, child.is_leaf)
self.keys.insert(i, child.keys[t - 1])
self.children.insert(i + 1, new_child)
new_child.keys = child.keys[t:]
child.keys = child.keys[:t - 1]
if not child.is_leaf:
new_child.children = child.children[t:]
child.children = child.children[:t]
def traverse(self):
for i in range(len(self.keys)):
if not self.is_leaf:
self.children[i].traverse()
print(self.keys[i], end=" ")
if not self.is_leaf:
self.children[-1].traverse()
def search(self, key):
i = 0
while i < len(self.keys) and key > self.keys[i]:
i += 1
if i < len(self.keys) and self.keys[i] == key:
return self
if self.is_leaf:
return None
return self.children[i].search(key)
def remove(self, key):
idx = 0
while idx < len(self.keys) and self.keys[idx] < key:
idx += 1
if idx < len(self.keys) and self.keys[idx] == key:
if self.is_leaf:
self.keys.pop(idx)
else:
self.remove_internal_node(idx)
elif not self.is_leaf:
flag = idx == len(self.keys)
if len(self.children[idx].keys) < self.t:
self.fill(idx)
if flag and idx > len(self.keys):
self.children[idx - 1].remove(key)
else:
self.children[idx].remove(key)
else:
print(f"Key {key} is not in the tree.")
def remove_internal_node(self, idx):
key = self.keys[idx]
if len(self.children[idx].keys) >= self.t:
pred = self.get_predecessor(idx)
self.keys[idx] = pred
self.children[idx].remove(pred)
elif len(self.children[idx + 1].keys) >= self.t:
succ = self.get_successor(idx)
self.keys[idx] = succ
self.children[idx + 1].remove(succ)
else:
self.merge(idx)
self.children[idx].remove(key)
def get_predecessor(self, idx):
cur = self.children[idx]
while not cur.is_leaf:
cur = cur.children[-1]
return cur.keys[-1]
def get_successor(self, idx):
cur = self.children[idx + 1]
while not cur.is_leaf:
cur = cur.children[0]
return cur.keys[0]
def fill(self, idx):
if idx != 0 and len(self.children[idx - 1].keys) >= self.t:
self.borrow_from_prev(idx)
elif idx != len(self.keys) and len(self.children[idx + 1].keys) >= self.t:
self.borrow_from_next(idx)
else:
if idx != len(self.keys):
self.merge(idx)
else:
self.merge(idx - 1)
def borrow_from_prev(self, idx):
child = self.children[idx]
sibling = self.children[idx - 1]
child.keys.insert(0, self.keys[idx - 1])
if not child.is_leaf:
child.children.insert(0, sibling.children.pop())
self.keys[idx - 1] = sibling.keys.pop()
def borrow_from_next(self, idx):
child = self.children[idx]
sibling = self.children[idx + 1]
child.keys.append(self.keys[idx])
if not child.is_leaf:
child.children.append(sibling.children.pop(0))
self.keys[idx] = sibling.keys.pop(0)
def merge(self, idx):
child = self.children[idx]
sibling = self.children[idx + 1]
child.keys.append(self.keys.pop(idx))
child.keys.extend(sibling.keys)
if not child.is_leaf:
child.children.extend(sibling.children)
self.children.pop(idx + 1)
class BTree:
def __init__(self, t):
self.root = BTreeNode(t, True)
self.t = t
def insert(self, key):
root = self.root
if len(root.keys) == 2 * self.t - 1:
new_root = BTreeNode(self.t, False)
new_root.children.append(self.root)
new_root.split_child(0)
i = 0
if new_root.keys[0] < key:
i += 1
new_root.children[i].insert_non_full(key)
self.root = new_root
else:
root.insert_non_full(key)
def traverse(self):
if self.root:
self.root.traverse()
def search(self, key):
if self.root:
return self.root.search(key)
return None
def delete(self, key):
if self.root:
self.root.remove(key)
if len(self.root.keys) == 0:
if self.root.is_leaf:
self.root = None
else:
self.root = self.root.children[0]
if __name__ == "__main__":
t = 3
b_tree = BTree(t)
while True:
print("\nOptions:")
print("1. Insert")
print("2. Traverse")
print("3. Search")
print("4. Delete")
print("5. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
key = int(input("Enter key to insert: "))
b_tree.insert(key)
elif choice == 2:
print("Traversal of the tree:")
b_tree.traverse()
print()
elif choice == 3:
key = int(input("Enter key to search: "))
result = b_tree.search(key)
if result:
print(f"Key {key} found in the tree.")
else:
print(f"Key {key} not found in the tree.")
elif choice == 4:
key = int(input("Enter key to delete: "))
b_tree.delete(key)
elif choice == 5:
break
else:
print("Invalid choice. Please try again.")