forked from TheAlgorithms/Python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathred_black_tree.py
More file actions
Latest commit
738 lines (675 loc) · 25.4 KB
/
Copy pathred_black_tree.py
File metadata and controls
738 lines (675 loc) · 25.4 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
"""
psf/black : true
ruff : passed
"""
from __future__ importannotations
fromcollections.abcimportIterator
classRedBlackTree:
"""
A Red-Black tree, which is a self-balancing BST (binary search
tree).
This tree has similar performance to AVL trees, but the balancing is
less strict, so it will perform faster for writing/deleting nodes
and slower for reading in the average case, though, because they're
both balanced binary search trees, both will get the same asymptotic
performance.
To read more about them, https://en.wikipedia.org/wiki/Red–black_tree
Unless otherwise specified, all asymptotic runtimes are specified in
terms of the size of the tree.
"""
def__init__(
self,
label: int|None=None,
color: int=0,
parent: RedBlackTree|None=None,
left: RedBlackTree|None=None,
right: RedBlackTree|None=None,
) ->None:
"""Initialize a new Red-Black Tree node with the given values:
label: The value associated with this node
color: 0 if black, 1 if red
parent: The parent to this node
left: This node's left child
right: This node's right child
"""
self.label=label
self.parent=parent
self.left=left
self.right=right
self.color=color
# Here are functions which are specific to red-black trees
defrotate_left(self) ->RedBlackTree:
"""Rotate the subtree rooted at this node to the left and
returns the new root to this subtree.
Performing one rotation can be done in O(1).
"""
parent=self.parent
right=self.right
ifrightisNone:
returnself
self.right=right.left
ifself.right:
self.right.parent=self
self.parent=right
right.left=self
ifparentisnotNone:
ifparent.left==self:
parent.left=right
else:
parent.right=right
right.parent=parent
returnright
defrotate_right(self) ->RedBlackTree:
"""Rotate the subtree rooted at this node to the right and
returns the new root to this subtree.
Performing one rotation can be done in O(1).
"""
ifself.leftisNone:
returnself
parent=self.parent
left=self.left
self.left=left.right
ifself.left:
self.left.parent=self
self.parent=left
left.right=self
ifparentisnotNone:
ifparent.rightisself:
parent.right=left
else:
parent.left=left
left.parent=parent
returnleft
definsert(self, label: int) ->RedBlackTree:
"""Inserts label into the subtree rooted at self, performs any
rotations necessary to maintain balance, and then returns the
new root to this subtree (likely self).
This is guaranteed to run in O(log(n)) time.
"""
ifself.labelisNone:
# Only possible with an empty tree
self.label=label
returnself
ifself.label==label:
returnself
elifself.label>label:
ifself.left:
self.left.insert(label)
else:
self.left=RedBlackTree(label, 1, self)
self.left._insert_repair()
else:
ifself.right:
self.right.insert(label)
else:
self.right=RedBlackTree(label, 1, self)
self.right._insert_repair()
returnself.parentorself
def_insert_repair(self) ->None:
"""Repair the coloring from inserting into a tree."""
ifself.parentisNone:
# This node is the root, so it just needs to be black
self.color=0
elifcolor(self.parent) ==0:
# If the parent is black, then it just needs to be red
self.color=1
else:
uncle=self.parent.sibling
ifcolor(uncle) ==0:
ifself.is_left() andself.parent.is_right():
self.parent.rotate_right()
ifself.right:
self.right._insert_repair()
elifself.is_right() andself.parent.is_left():
self.parent.rotate_left()
ifself.left:
self.left._insert_repair()
elifself.is_left():
ifself.grandparent:
self.grandparent.rotate_right()
self.parent.color=0
ifself.parent.right:
self.parent.right.color=1
else:
ifself.grandparent:
self.grandparent.rotate_left()
self.parent.color=0
ifself.parent.left:
self.parent.left.color=1
else:
self.parent.color=0
ifuncleandself.grandparent:
uncle.color=0
self.grandparent.color=1
self.grandparent._insert_repair()
defremove(self, label: int) ->RedBlackTree: # noqa: PLR0912
"""Remove label from this tree."""
ifself.label==label:
ifself.leftandself.right:
# It's easier to balance a node with at most one child,
# so we replace this node with the greatest one less than
# it and remove that.
value=self.left.get_max()
ifvalueisnotNone:
self.label=value
self.left.remove(value)
else:
# This node has at most one non-None child, so we don't
# need to replace
child=self.leftorself.right
ifself.color==1:
# This node is red, and its child is black
# The only way this happens to a node with one child
# is if both children are None leaves.
# We can just remove this node and call it a day.
ifself.parent:
ifself.is_left():
self.parent.left=None
else:
self.parent.right=None
else:
# The node is black
ifchildisNone:
# This node and its child are black
ifself.parentisNone:
# The tree is now empty
returnRedBlackTree(None)
else:
self._remove_repair()
ifself.is_left():
self.parent.left=None
else:
self.parent.right=None
self.parent=None
else:
# This node is black and its child is red
# Move the child node here and make it black
self.label=child.label
self.left=child.left
self.right=child.right
ifself.left:
self.left.parent=self
ifself.right:
self.right.parent=self
elifself.labelisnotNoneandself.label>label:
ifself.left:
self.left.remove(label)
else:
ifself.right:
self.right.remove(label)
returnself.parentorself
def_remove_repair(self) ->None:
"""Repair the coloring of the tree that may have been messed up."""
if (
self.parentisNone
orself.siblingisNone
orself.parent.siblingisNone
orself.grandparentisNone
):
return
ifcolor(self.sibling) ==1:
self.sibling.color=0
self.parent.color=1
ifself.is_left():
self.parent.rotate_left()
else:
self.parent.rotate_right()
if (
color(self.parent) ==0
andcolor(self.sibling) ==0
andcolor(self.sibling.left) ==0
andcolor(self.sibling.right) ==0
):
self.sibling.color=1
self.parent._remove_repair()
return
if (
color(self.parent) ==1
andcolor(self.sibling) ==0
andcolor(self.sibling.left) ==0
andcolor(self.sibling.right) ==0
):
self.sibling.color=1
self.parent.color=0
return
if (
self.is_left()
andcolor(self.sibling) ==0
andcolor(self.sibling.right) ==0
andcolor(self.sibling.left) ==1
):
self.sibling.rotate_right()
self.sibling.color=0
ifself.sibling.right:
self.sibling.right.color=1
if (
self.is_right()
andcolor(self.sibling) ==0
andcolor(self.sibling.right) ==1
andcolor(self.sibling.left) ==0
):
self.sibling.rotate_left()
self.sibling.color=0
ifself.sibling.left:
self.sibling.left.color=1
if (
self.is_left()
andcolor(self.sibling) ==0
andcolor(self.sibling.right) ==1
):
self.parent.rotate_left()
self.grandparent.color=self.parent.color
self.parent.color=0
self.parent.sibling.color=0
if (
self.is_right()
andcolor(self.sibling) ==0
andcolor(self.sibling.left) ==1
):
self.parent.rotate_right()
self.grandparent.color=self.parent.color
self.parent.color=0
self.parent.sibling.color=0
defcheck_color_properties(self) ->bool:
"""Check the coloring of the tree, and return True iff the tree
is colored in a way which matches these five properties:
(wording stolen from wikipedia article)
1. Each node is either red or black.
2. The root node is black.
3. All leaves are black.
4. If a node is red, then both its children are black.
5. Every path from any node to all of its descendent NIL nodes
has the same number of black nodes.
This function runs in O(n) time, because properties 4 and 5 take
that long to check.
"""
# I assume property 1 to hold because there is nothing that can
# make the color be anything other than 0 or 1.
# Property 2
ifself.color:
# The root was red
print("Property 2")
returnFalse
# Property 3 does not need to be checked, because None is assumed
# to be black and is all the leaves.
# Property 4
ifnotself.check_coloring():
print("Property 4")
returnFalse
# Property 5
ifself.black_height() isNone:
print("Property 5")
returnFalse
# All properties were met
returnTrue
defcheck_coloring(self) ->bool:
"""A helper function to recursively check Property 4 of a
Red-Black Tree. See check_color_properties for more info.
"""
ifself.color==1and1in (color(self.left), color(self.right)):
returnFalse
ifself.leftandnotself.left.check_coloring():
returnFalse
ifself.rightandnotself.right.check_coloring():
returnFalse
returnTrue
defblack_height(self) ->int|None:
"""Returns the number of black nodes from this node to the
leaves of the tree, or None if there isn't one such value (the
tree is color incorrectly).
"""
ifselfisNoneorself.leftisNoneorself.rightisNone:
# If we're already at a leaf, there is no path
return1
left=RedBlackTree.black_height(self.left)
right=RedBlackTree.black_height(self.right)
ifleftisNoneorrightisNone:
# There are issues with coloring below children nodes
returnNone
ifleft!=right:
# The two children have unequal depths
returnNone
# Return the black depth of children, plus one if this node is
# black
returnleft+ (1-self.color)
# Here are functions which are general to all binary search trees
def__contains__(self, label: int) ->bool:
"""Search through the tree for label, returning True iff it is
found somewhere in the tree.
Guaranteed to run in O(log(n)) time.
"""
returnself.search(label) isnotNone
defsearch(self, label: int) ->RedBlackTree|None:
"""Search through the tree for label, returning its node if
it's found, and None otherwise.
This method is guaranteed to run in O(log(n)) time.
"""
ifself.label==label:
returnself
elifself.labelisnotNoneandlabel>self.label:
ifself.rightisNone:
returnNone
else:
returnself.right.search(label)
else:
ifself.leftisNone:
returnNone
else:
returnself.left.search(label)
deffloor(self, label: int) ->int|None:
"""Returns the largest element in this tree which is at most label.
This method is guaranteed to run in O(log(n)) time."""
ifself.label==label:
returnself.label
elifself.labelisnotNoneandself.label>label:
ifself.left:
returnself.left.floor(label)
else:
returnNone
else:
ifself.right:
attempt=self.right.floor(label)
ifattemptisnotNone:
returnattempt
returnself.label
defceil(self, label: int) ->int|None:
"""Returns the smallest element in this tree which is at least label.
This method is guaranteed to run in O(log(n)) time.
"""
ifself.label==label:
returnself.label
elifself.labelisnotNoneandself.label<label:
ifself.right:
returnself.right.ceil(label)
else:
returnNone
else:
ifself.left:
attempt=self.left.ceil(label)
ifattemptisnotNone:
returnattempt
returnself.label
defget_max(self) ->int|None:
"""Returns the largest element in this tree.
This method is guaranteed to run in O(log(n)) time.
"""
ifself.right:
# Go as far right as possible
returnself.right.get_max()
else:
returnself.label
defget_min(self) ->int|None:
"""Returns the smallest element in this tree.
This method is guaranteed to run in O(log(n)) time.
"""
ifself.left:
# Go as far left as possible
returnself.left.get_min()
else:
returnself.label
@property
defgrandparent(self) ->RedBlackTree|None:
"""Get the current node's grandparent, or None if it doesn't exist."""
ifself.parentisNone:
returnNone
else:
returnself.parent.parent
@property
defsibling(self) ->RedBlackTree|None:
"""Get the current node's sibling, or None if it doesn't exist."""
ifself.parentisNone:
returnNone
elifself.parent.leftisself:
returnself.parent.right
else:
returnself.parent.left
defis_left(self) ->bool:
"""Returns true iff this node is the left child of its parent."""
ifself.parentisNone:
returnFalse
returnself.parent.leftisself.parent.leftisself
defis_right(self) ->bool:
"""Returns true iff this node is the right child of its parent."""
ifself.parentisNone:
returnFalse
returnself.parent.rightisself
def__bool__(self) ->bool:
returnTrue
def__len__(self) ->int:
"""
Return the number of nodes in this tree.
"""
ln=1
ifself.left:
ln+=len(self.left)
ifself.right:
ln+=len(self.right)
returnln
defpreorder_traverse(self) ->Iterator[int|None]:
yieldself.label
ifself.left:
yieldfromself.left.preorder_traverse()
ifself.right:
yieldfromself.right.preorder_traverse()
definorder_traverse(self) ->Iterator[int|None]:
ifself.left:
yieldfromself.left.inorder_traverse()
yieldself.label
ifself.right:
yieldfromself.right.inorder_traverse()
defpostorder_traverse(self) ->Iterator[int|None]:
ifself.left:
yieldfromself.left.postorder_traverse()
ifself.right:
yieldfromself.right.postorder_traverse()
yieldself.label
def__repr__(self) ->str:
frompprintimportpformat
ifself.leftisNoneandself.rightisNone:
returnf"'{self.label}{(self.colorand'red') or'blk'}'"
returnpformat(
{
f"{self.label}{(self.colorand'red') or'blk'}": (
self.left,
self.right,
)
},
indent=1,
)
def__eq__(self, other: object) ->bool:
"""Test if two trees are equal."""
ifnotisinstance(other, RedBlackTree):
returnNotImplemented
ifself.label==other.label:
returnself.left==other.leftandself.right==other.right
else:
returnFalse
defcolor(node: RedBlackTree|None) ->int:
"""Returns the color of a node, allowing for None leaves."""
ifnodeisNone:
return0
else:
returnnode.color
"""
Code for testing the various
functions of the red-black tree.
"""
deftest_rotations() ->bool:
"""Test that the rotate_left and rotate_right functions work."""
# Make a tree to test on
tree=RedBlackTree(0)
tree.left=RedBlackTree(-10, parent=tree)
tree.right=RedBlackTree(10, parent=tree)
tree.left.left=RedBlackTree(-20, parent=tree.left)
tree.left.right=RedBlackTree(-5, parent=tree.left)
tree.right.left=RedBlackTree(5, parent=tree.right)
tree.right.right=RedBlackTree(20, parent=tree.right)
# Make the right rotation
left_rot=RedBlackTree(10)
left_rot.left=RedBlackTree(0, parent=left_rot)
left_rot.left.left=RedBlackTree(-10, parent=left_rot.left)
left_rot.left.right=RedBlackTree(5, parent=left_rot.left)
left_rot.left.left.left=RedBlackTree(-20, parent=left_rot.left.left)
left_rot.left.left.right=RedBlackTree(-5, parent=left_rot.left.left)
left_rot.right=RedBlackTree(20, parent=left_rot)
tree=tree.rotate_left()
iftree!=left_rot:
returnFalse
tree=tree.rotate_right()
tree=tree.rotate_right()
# Make the left rotation
right_rot=RedBlackTree(-10)
right_rot.left=RedBlackTree(-20, parent=right_rot)
right_rot.right=RedBlackTree(0, parent=right_rot)
right_rot.right.left=RedBlackTree(-5, parent=right_rot.right)
right_rot.right.right=RedBlackTree(10, parent=right_rot.right)
right_rot.right.right.left=RedBlackTree(5, parent=right_rot.right.right)
right_rot.right.right.right=RedBlackTree(20, parent=right_rot.right.right)
iftree!=right_rot:
returnFalse
returnTrue
deftest_insertion_speed() ->bool:
"""Test that the tree balances inserts to O(log(n)) by doing a lot
of them.
"""
tree=RedBlackTree(-1)
foriinrange(300000):
tree=tree.insert(i)
returnTrue
deftest_insert() ->bool:
"""Test the insert() method of the tree correctly balances, colors,
and inserts.
"""
tree=RedBlackTree(0)
tree.insert(8)
tree.insert(-8)
tree.insert(4)
tree.insert(12)
tree.insert(10)
tree.insert(11)
ans=RedBlackTree(0, 0)
ans.left=RedBlackTree(-8, 0, ans)
ans.right=RedBlackTree(8, 1, ans)
ans.right.left=RedBlackTree(4, 0, ans.right)
ans.right.right=RedBlackTree(11, 0, ans.right)
ans.right.right.left=RedBlackTree(10, 1, ans.right.right)
ans.right.right.right=RedBlackTree(12, 1, ans.right.right)
returntree==ans
deftest_insert_and_search() ->bool:
"""Tests searching through the tree for values."""
tree=RedBlackTree(0)
tree.insert(8)
tree.insert(-8)
tree.insert(4)
tree.insert(12)
tree.insert(10)
tree.insert(11)
if5intreeor-6intreeor-10intreeor13intree:
# Found something not in there
returnFalse
ifnot (11intreeand12intreeand-8intreeand0intree):
# Didn't find something in there
returnFalse
returnTrue
deftest_insert_delete() ->bool:
"""Test the insert() and delete() method of the tree, verifying the
insertion and removal of elements, and the balancing of the tree.
"""
tree=RedBlackTree(0)
tree=tree.insert(-12)
tree=tree.insert(8)
tree=tree.insert(-8)
tree=tree.insert(15)
tree=tree.insert(4)
tree=tree.insert(12)
tree=tree.insert(10)
tree=tree.insert(9)
tree=tree.insert(11)
tree=tree.remove(15)
tree=tree.remove(-12)
tree=tree.remove(9)
ifnottree.check_color_properties():
returnFalse
iflist(tree.inorder_traverse()) != [-8, 0, 4, 8, 10, 11, 12]:
returnFalse
returnTrue
deftest_floor_ceil() ->bool:
"""Tests the floor and ceiling functions in the tree."""
tree=RedBlackTree(0)
tree.insert(-16)
tree.insert(16)
tree.insert(8)
tree.insert(24)
tree.insert(20)
tree.insert(22)
tuples= [(-20, None, -16), (-10, -16, 0), (8, 8, 8), (50, 24, None)]
forval, floor, ceilintuples:
iftree.floor(val) !=floorortree.ceil(val) !=ceil:
returnFalse
returnTrue
deftest_min_max() ->bool:
"""Tests the min and max functions in the tree."""
tree=RedBlackTree(0)
tree.insert(-16)
tree.insert(16)
tree.insert(8)
tree.insert(24)
tree.insert(20)
tree.insert(22)
iftree.get_max() !=22ortree.get_min() !=-16:
returnFalse
returnTrue
deftest_tree_traversal() ->bool:
"""Tests the three different tree traversal functions."""
tree=RedBlackTree(0)
tree=tree.insert(-16)
tree.insert(16)
tree.insert(8)
tree.insert(24)
tree.insert(20)
tree.insert(22)
iflist(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]:
returnFalse
iflist(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]:
returnFalse
iflist(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]:
returnFalse
returnTrue
deftest_tree_chaining() ->bool:
"""Tests the three different tree chaining functions."""
tree=RedBlackTree(0)
tree=tree.insert(-16).insert(16).insert(8).insert(24).insert(20).insert(22)
iflist(tree.inorder_traverse()) != [-16, 0, 8, 16, 20, 22, 24]:
returnFalse
iflist(tree.preorder_traverse()) != [0, -16, 16, 8, 22, 20, 24]:
returnFalse
iflist(tree.postorder_traverse()) != [-16, 8, 20, 24, 22, 16, 0]:
returnFalse
returnTrue
defprint_results(msg: str, passes: bool) ->None:
print(str(msg), "works!"ifpasseselse"doesn't work :(")
defpytests() ->None:
asserttest_rotations()
asserttest_insert()
asserttest_insert_and_search()
asserttest_insert_delete()
asserttest_floor_ceil()
asserttest_tree_traversal()
asserttest_tree_chaining()
defmain() ->None:
"""
>>> pytests()
"""
print_results("Rotating right and left", test_rotations())
print_results("Inserting", test_insert())
print_results("Searching", test_insert_and_search())
print_results("Deleting", test_insert_delete())
print_results("Floor and ceil", test_floor_ceil())
print_results("Tree traversal", test_tree_traversal())
print_results("Tree traversal", test_tree_chaining())
print("Testing tree balancing...")
print("This should only be a few seconds.")
test_insertion_speed()
print("Done!")
if__name__=="__main__":
main()