| 1 | # A red-black binary tree data-structure. | ||
| 2 | # | ||
| 3 | # Mostly from the Cormen-Leiserson-Rivest book. | ||
| 4 | |||
| 5 | package DataStructure::RedBlackBTree; | ||
| 6 | |||
| 7 | use strict; | ||
| 8 | use warnings; | ||
| 9 | use utf8; | ||
| 10 | use feature ':5.24'; | ||
| 11 | use feature 'signatures'; | ||
| 12 | no warnings 'experimental::signatures'; | ||
| 13 | |||
| 14 | use DataStructure::BTree; | ||
| 15 | use DataStructure::BTree::Node; | ||
| 16 | |||
| 17 | use parent qw(DataStructure::OrderedSet); | ||
| 18 | |||
| 19 | our @ISA = ('DataStructure::BTree'); | ||
| 20 | |||
| 21 | sub new ($class, %options) { | ||
| 22 | $options{_context_skip} += 1; | ||
| 23 | return $class->SUPER::new(%options); | ||
| 24 | } | ||
| 25 | |||
| 26 | sub insert ($self, $value, $hint = undef) { | ||
| 27 | my $n = $self->SUPER::insert($value, $hint); | ||
| 28 | $n->{color} = 'R'; | ||
| 29 | while (defined $n->{parent} && $n->{parent}{color} eq 'R') { | ||
| 30 | if ($n->{parent} == $n->{parent}{parent}{left}) { | ||
| 31 | my $m = $n->{parent}{parent}{right}; | ||
| 32 | if ($m->{color} eq 'R') { | ||
| 33 | $n->{parent}{color} = 'B'; | ||
| 34 | $m->{color} = 'B'; | ||
| 35 | $n->{parent}{parent}{color} = 'R'; | ||
| 36 | $n = $n->{parent}{parent}; | ||
| 37 | } else { | ||
| 38 | if ($n == $n->{parent}{right}) { | ||
| 39 | $n = $n->{parent}; | ||
| 40 | $n->_rotate_left(); | ||
| 41 | } | ||
| 42 | $n->{parent}{color} = 'B'; | ||
| 43 | $n->{parent}{parent}{color} = 'R'; | ||
| 44 | $n->{parent}{parent}->_rotate_right(); | ||
| 45 | } | ||
| 46 | } else { | ||
| 47 | my $m = $n->{parent}{parent}{left}; | ||
| 48 | if ($m->{color} eq 'R') { | ||
| 49 | $n->{parent}{color} = 'B'; | ||
| 50 | $m->{color} = 'B'; | ||
| 51 | $n->{parent}{parent}{color} = 'R'; | ||
| 52 | $n = $n->{parent}{parent}; | ||
| 53 | } else { | ||
| 54 | if ($n == $n->{parent}{left}) { | ||
| 55 | $n = $n->{parent}; | ||
| 56 | $n->_rotate_right(); | ||
| 57 | } | ||
| 58 | $n->{parent}{color} = 'B'; | ||
| 59 | $n->{parent}{parent}{color} = 'R'; | ||
| 60 | $n->{parent}{parent}->_rotate_left(); | ||
| 61 | } | ||
| 62 | } | ||
| 63 | } | ||
| 64 | return; | ||
| 65 | } |