-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedBlackTree.py
More file actions
executable file
·439 lines (368 loc) · 14.3 KB
/
RedBlackTree.py
File metadata and controls
executable file
·439 lines (368 loc) · 14.3 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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
# This is code is adopted from zybooks.com
# Govinda KC
# CS2302 lab3A
class RBTNode:
def __init__(self, key, embedding, parent, is_red = False, left = None, right = None):
self.key = key
self.embedding = embedding
self.left = left
self.right = right
self.parent = parent
if is_red:
self.color = "red"
else:
self.color = "black"
# Returns true if both child nodes are black. A child set to None is considered
# to be black.
def are_both_children_black(self):
if self.left != None and self.left.is_red():
return False
if self.right != None and self.right.is_red():
return False
return True
def count(self):
count = 1
if self.left != None:
count = count + self.left.count()
if self.right != None:
count = count + self.right.count()
return count
# Returns the grandparent of this node
def get_grandparent(self):
if self.parent is None:
return None
return self.parent.parent
# Gets this node's predecessor from the left child subtree
# Precondition: This node's left child is not None
def get_predecessor(self):
node = self.left
while node.right is not None:
node = node.right
return node
# Returns this node's sibling, or None if this node does not have a sibling
def get_sibling(self):
if self.parent is not None:
if self is self.parent.left:
return self.parent.right
return self.parent.left
return None
# Returns the uncle of this node
def get_uncle(self):
grandparent = self.get_grandparent()
if grandparent is None:
return None
if grandparent.left is self.parent:
return grandparent.right
return grandparent.left
# Returns True if this node is black, False otherwise
def is_black(self):
return self.color == "black"
# Returns True if this node is red, False otherwise
def is_red(self):
return self.color == "red"
# Replaces one of this node's children with a new child
def replace_child(self, current_child, new_child):
if self.left is current_child:
return self.set_child("left", new_child)
elif self.right is current_child:
return self.set_child("right", new_child)
return False
# Sets either the left or right child of this node
def set_child(self, which_child, child):
if which_child != "left" and which_child != "right":
return False
if which_child == "left":
self.left = child
else:
self.right = child
if child != None:
child.parent = self
return True
def get_embedding(self):
if self.embedding is not None:
return self.embedding
def set_embedding(self, array):
self.embedding = array
class RedBlackTree:
def __init__(self):
self.root = None
def __len__(self):
if self.root is None:
return 0
return self.root.count()
def _bst_remove(self, key):
node = self.search(key)
self._bst_remove_node(node)
def _bst_remove_node(self, node):
if node is None:
return
# Case 1: Internal node with 2 children
if node.left is not None and node.right is not None:
# Find successor
successor_node = node.right
while successor_node.left is not None:
successor_node = successor_node.left
# Copy successor's key
successor_key = successor_node.key
# Recursively remove successor
self._bst_remove_node(successor_node)
# Set node's key to copied successor key
node.key = successor_key
# Case 2: Root node (with 1 or 0 children)
elif node is self.root:
if node.left is not None:
self.root = node.left
else:
self.root = node.right
# Make sure the new root, if not None, has parent set to None
if self.root is not None:
self.root.parent = None
# Case 3: Internal with left child only
elif node.left is not None:
node.parent.replace_child(node, node.left)
# Case 4: Internal with right child OR leaf
else:
node.parent.replace_child(node, node.right)
# Writes nodes at distance k from root to file.
def _depth(self, k):
_dep = self._depth_total(self.root, k)
f=open("RB_depth.txt", "a+")
for i in range (len(_dep)):
f.write(str(_dep[i]+" \n"))
f.close()
return None
def _depth_total(self, node, k):
arr = []
if node is None:
return
if k==0:
arr.append(node.key)
else:
arr = arr + self._depth_total(node.left, k-1)
arr = arr + self._depth_total(node.right, k-1)
return arr
# Returns the height of this tree
def _height(self):
return self._height_total(self.root)
def _height_total(self, node):
if node is None:
return -1
left_height = self._height_total(node.left)
right_height = self._height_total(node.right)
return 1 + max(left_height, right_height)
# writes tree in ascending order to file
def _write(self):
_ascend = self._write_afile(self.root)
f=open("RedBlack_tree.txt", "a+", encoding="utf-8")
for i in range (len(_ascend)):
f.write(str(_ascend[i])+" \n")
f.close()
return None
def _write_afile(self, node):
arr = []
if node:
arr = self._write_afile(node.left)
arr.append(node.key)
arr = arr + self._write_afile(node.right)
return arr
def insert(self, key, embedding):
new_node = RBTNode(key, embedding, None, True, None, None)
self.insert_node(new_node)
def insert_node(self, node):
# Begin with normal BST insertion
if self.root is None:
# Special case for root
self.root = node
else:
current_node = self.root
while current_node is not None:
if node.key < current_node.key:
if current_node.left is None:
current_node.set_child("left", node)
break
else:
current_node = current_node.left
else:
if current_node.right is None:
current_node.set_child("right", node)
break
else:
current_node = current_node.right
# Color the node red
node.color = "red"
# Balance
self.insertion_balance(node)
def insertion_balance(self, node):
# If node is the tree's root, then color node black and return
if node.parent is None:
node.color = "black"
return
# If parent is black, then return without any alterations
if node.parent.is_black():
return
# References to parent, grandparent, and uncle are needed for remaining operations
parent = node.parent
grandparent = node.get_grandparent()
uncle = node.get_uncle()
# If parent and uncle are both red, then color parent and uncle black, color grandparent
# red, recursively balance grandparent, then return
if uncle is not None and uncle.is_red():
parent.color = uncle.color = "black"
grandparent.color = "red"
self.insertion_balance(grandparent)
return
# If node is parent's right child and parent is grandparent's left child, then rotate left
# at parent, update node and parent to point to parent and grandparent, respectively
if node is parent.right and parent is grandparent.left:
self.rotate_left(parent)
node = parent
parent = node.parent
# Else if node is parent's left child and parent is grandparent's right child, then rotate
# right at parent, update node and parent to point to parent and grandparent, respectively
elif node is parent.left and parent is grandparent.right:
self.rotate_right(parent)
node = parent
parent = node.parent
# Color parent black and grandparent red
parent.color = "black"
grandparent.color = "red"
# If node is parent's left child, then rotate right at grandparent, otherwise rotate left
# at grandparent
if node is parent.left:
self.rotate_right(grandparent)
else:
self.rotate_left(grandparent)
# Performs an in-order traversal, calling the visitor function for each node in the tree
def in_order(self, visitor_function):
self.in_order_recursive(visitor_function, self.root)
# Performs an in-order traversal
def in_order_recursive(self, visitor_function, node):
if node is None:
return
# Left subtree, then node, then right subtree
self.in_order_recursive(visitor_function, node.left)
visitor_function(node)
self.in_order_recursive(visitor_function, node.right)
def is_none_or_black(self, node):
if node is None:
return True
return node.is_black()
def is_not_none_and_red(self, node):
if node is None:
return False
return node.is_red()
def prepare_for_removal(self, node):
if self.try_case1(node):
return
sibling = node.get_sibling()
if self.try_case2(node, sibling):
sibling = node.get_sibling()
if self.try_case3(node, sibling):
return
if self.try_case4(node, sibling):
return
if self.try_case5(node, sibling):
sibling = node.get_sibling()
if self.try_case6(node, sibling):
sibling = node.get_sibling()
sibling.color = node.parent.color
node.parent.color = "black"
if node is node.parent.left:
sibling.right.color = "black"
self.rotate_left(node.parent)
else:
sibling.left.color = "black"
self.rotate_right(node.parent)
def remove(self, key):
node = self.search(key)
if node is not None:
self.remove_node(node)
return True
return False
def remove_node(self, node):
if node.left is not None and node.right is not None:
predecessor_node = node.get_predecessor()
predecessor_key = predecessor_node.key
self.remove_node(predecessor_node)
node.key = predecessor_key
return
if node.is_black():
self.prepare_for_removal(node)
self._bst_remove(node.key)
# One special case if the root was changed to red
if self.root is not None and self.root.is_red():
self.root.color = "black"
def rotate_left(self, node):
right_left_child = node.right.left
if node.parent != None:
node.parent.replace_child(node, node.right)
else: # node is root
self.root = node.right
self.root.parent = None
node.right.set_child("left", node)
node.set_child("right", right_left_child)
def rotate_right(self, node):
left_right_child = node.left.right
if node.parent != None:
node.parent.replace_child(node, node.left)
else: # node is root
self.root = node.left
self.root.parent = None
node.left.set_child("right", node)
node.set_child("left", left_right_child)
def search(self, key):
current_node = self.root
while current_node is not None:
# Return the node if the key matches.
if current_node.key == key:
return current_node
# Navigate to the left if the search key is
# less than the node's key.
elif key < current_node.key:
current_node = current_node.left
# Navigate to the right if the search key is
# greater than the node's key.
else:
current_node = current_node.right
# The key was not found in the tree.
return None
def try_case1(self, node):
if node.is_red() or node.parent is None:
return True
return False # node case 1
def try_case2(self, node, sibling):
if sibling.is_red():
node.parent.color = "red"
sibling.color = "black"
if node is node.parent.left:
self.rotate_left(node.parent)
else:
self.rotate_right(node.parent)
return True
return False # not case 2
def try_case3(self, node, sibling):
if node.parent.is_black() and sibling.are_both_children_black():
sibling.color = "red"
self.prepare_for_removal(node.parent)
return True
return False # not case 3
def try_case4(self, node, sibling):
if node.parent.is_red() and sibling.are_both_children_black():
node.parent.color = "black"
sibling.color = "red"
return True
return False # not case 4
def try_case5(self, node, sibling):
if self.is_not_none_and_red(sibling.left) and self.is_none_or_black(sibling.right) and node is node.parent.left:
sibling.color = "red"
sibling.left.color = "black"
self.rotate_right(sibling)
return True
return False # not case 5
def try_case6(self, node, sibling):
if self.is_none_or_black(sibling.left) and self.is_not_none_and_red(sibling.right) and node is node.parent.right:
sibling.color = "red"
sibling.right.color = "black"
self.rotate_left(sibling)
return True
return False # not case 6