Class: Tree::RedBlackNode
- Inherits:
-
Object
- Object
- Tree::RedBlackNode
- Includes:
- Enumerable
- Defined in:
- lib/tree/red_black/red_black_node.rb
Overview
Tree::RedBlackNode is a pure-Ruby implementation of a Red-Black tree – i.e., a self-balancing binary search tree with O(log n) search, insert and delete operations. It is appropriate for maintaining an ordered collection where insertion and deletion are desired at arbitrary positions.
The implementation differs slightly from the Wikipedia description referenced above. In particular, leaf nodes are nil
, which affects the details of node deletion.
While a Red-Black tree can be constructed from nodes alone, the Tree::RedBlack API provides a cleaner way of working with Red-Black trees. Start there if only using the Red-Black tree as a container.
Instance Attribute Summary collapse
-
#color ⇒ Object
Returns the value of attribute color.
-
#key ⇒ Object
Returns the value of attribute key.
-
#left ⇒ Object
Returns the value of attribute left.
-
#parent ⇒ Object
Returns the value of attribute parent.
-
#right ⇒ Object
Returns the value of attribute right.
Instance Method Summary collapse
-
#<=>(other) ⇒ Object
:nodoc:.
-
#bsearch(&block) ⇒ Object
Returns a node satisfying a criterion defined in
block
by binary search. -
#color_delete_left ⇒ Object
:nodoc:.
-
#color_delete_right ⇒ Object
:nodoc:.
-
#color_insert ⇒ Object
:nodoc:.
-
#delete_red_black(value) ⇒ Object
Deletes the given
value
from a tree whose root node isself
. -
#dup ⇒ Object
Returns a deep copy of the tree with root
self
, provided that thedup
method for thekey
attribute of a node is also a deep copy. -
#grandparent ⇒ Object
:nodoc:.
-
#in_order {|_self| ... } ⇒ Object
(also: #each)
Returns an enumerator for nodes in the tree with root
self
by in-order traversal. -
#initialize(value = nil, color = :RED) ⇒ RedBlackNode
constructor
Example.
-
#insert_key(value) ⇒ Object
:nodoc:.
-
#insert_red_black(value, allow_duplicates = true) ⇒ Object
Since a Red-Black tree maintains an ordered, Enumerable collection, every value inserted must be Comparable with every other value.
-
#insert_unique_key(value) ⇒ Object
:nodoc:.
-
#max ⇒ Object
Returns the node whose
key
is a maximum in the sub-tree with rootself
. -
#min ⇒ Object
Returns the node whose
key
is a minimum in the sub-tree with rootself
. -
#parent_sibling ⇒ Object
:nodoc:.
-
#pre_order {|_self| ... } ⇒ Object
Returns an enumerator for nodes in the tree with root
self
by pre-order traversal. -
#pred ⇒ Object
Returns the node preceding
self
, ornil
if no predecessor exists. -
#rotate_left ⇒ Object
:nodoc:.
-
#rotate_right ⇒ Object
:nodoc:.
-
#search(value, ifnone = nil) ⇒ Object
Returns a node whose
key
matchesvalue
by binary search. -
#sibling ⇒ Object
:nodoc:.
-
#substitute_with_child ⇒ Object
:nodoc:.
-
#succ ⇒ Object
Returns the node succeeding
self
, ornil
if no successor exists.
Constructor Details
#initialize(value = nil, color = :RED) ⇒ RedBlackNode
53 54 55 56 57 58 59 |
# File 'lib/tree/red_black/red_black_node.rb', line 53 def initialize(value = nil, color = :RED) raise "color must be :RED or :BLACK" unless [:RED, :BLACK].include?(color) @left = @right = @parent = nil @key = value @color = color end |
Instance Attribute Details
#color ⇒ Object
Returns the value of attribute color.
24 25 26 |
# File 'lib/tree/red_black/red_black_node.rb', line 24 def color @color end |
#key ⇒ Object
Returns the value of attribute key.
24 25 26 |
# File 'lib/tree/red_black/red_black_node.rb', line 24 def key @key end |
#left ⇒ Object
Returns the value of attribute left.
24 25 26 |
# File 'lib/tree/red_black/red_black_node.rb', line 24 def left @left end |
#parent ⇒ Object
Returns the value of attribute parent.
24 25 26 |
# File 'lib/tree/red_black/red_black_node.rb', line 24 def parent @parent end |
#right ⇒ Object
Returns the value of attribute right.
24 25 26 |
# File 'lib/tree/red_black/red_black_node.rb', line 24 def right @right end |
Instance Method Details
#<=>(other) ⇒ Object
:nodoc:
61 62 63 |
# File 'lib/tree/red_black/red_black_node.rb', line 61 def <=>(other) # :nodoc: key <=> other.key end |
#bsearch(&block) ⇒ Object
Returns a node satisfying a criterion defined in block
by binary search.
If block
evaluates to true
or false
, returns the first node for which the block
evaluates to true
. In this case, the criterion is expected to return false
for nodes preceding the matching node and true
for subsequent nodes.
Example
require 'tree/red_black'
shuffled_values = [*1..10].shuffle
root = shuffled_values.reduce(Tree::RedBlackNode.new) do |acc, v|
acc.insert_red_black(v)
end
root.bsearch { |node| node.key >= 7 }
#=> <Tree::RedBlackNode:0x00... @key=7 ...>
If block
evaluates to <0
, 0
or >0
, returns first node for which block
evaluates to 0
. Otherwise returns nil
. In this case, the criterion is expected to return <0
for nodes preceding the matching node, 0
for some subsequent nodes and >0
for nodes beyond that.
Example
require 'tree/red_black'
shuffled_values = [*1..10].shuffle
root = shuffled_values.reduce(Tree::RedBlackNode.new) do |acc, v|
acc.insert_red_black(v)
end
root.bsearch { |node| 7 <=> node.key }
#=> <Tree::RedBlackNode:0x00... @key=7 ...>
If block+
is not given, returns an enumerator.
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 |
# File 'lib/tree/red_black/red_black_node.rb', line 228 def bsearch(&block) return enum_for(:bsearch) unless block_given? return nil if key.nil? result = block.call(self) case result when Integer if result > 0 right ? right.bsearch(&block) : nil elsif result < 0 left ? left.bsearch(&block) : nil else self end when TrueClass, FalseClass if result left ? (node = left.bsearch(&block); node ? node : self) : self else right ? right.bsearch(&block) : nil end else nil end end |
#color_delete_left ⇒ Object
:nodoc:
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 |
# File 'lib/tree/red_black/red_black_node.rb', line 565 def color_delete_left # :nodoc: child_sibling = right if child_sibling.color == :RED @color = :RED child_sibling.color = :BLACK rotate_left child_sibling = right end if (color == :BLACK && child_sibling.color == :BLACK && (child_sibling.left.nil? || child_sibling.left.color == :BLACK) && (child_sibling.right.nil? || child_sibling.right.color == :BLACK)) child_sibling.color = :RED if self == parent&.left parent.color_delete_left elsif self == parent&.right parent.color_delete_right end elsif (color == :RED && child_sibling.color == :BLACK && (child_sibling.left.nil? || child_sibling.left.color == :BLACK) && (child_sibling.right.nil? || child_sibling.right.color == :BLACK)) child_sibling.color = :RED @color = :BLACK else if child_sibling.color == :BLACK if ((child_sibling.right.nil? || child_sibling.right.color == :BLACK) && child_sibling.left&.color == :RED) child_sibling.color = :RED child_sibling.left.color = :BLACK child_sibling.rotate_right child_sibling = right end end child_sibling.color = color @color = :BLACK child_sibling.right.color = :BLACK # if child_sibling.right rotate_left end end |
#color_delete_right ⇒ Object
:nodoc:
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 |
# File 'lib/tree/red_black/red_black_node.rb', line 521 def color_delete_right # :nodoc: child_sibling = left if child_sibling.color == :RED @color = :RED child_sibling.color = :BLACK rotate_right child_sibling = left end if (color == :BLACK && child_sibling.color == :BLACK && (child_sibling.left.nil? || child_sibling.left.color == :BLACK) && (child_sibling.right.nil? || child_sibling.right.color == :BLACK)) child_sibling.color = :RED if self == parent&.left parent.color_delete_left elsif self == parent&.right parent.color_delete_right end elsif (color == :RED && child_sibling.color == :BLACK && (child_sibling.left.nil? || child_sibling.left.color == :BLACK) && (child_sibling.right.nil? || child_sibling.right.color == :BLACK)) child_sibling.color = :RED @color = :BLACK else if child_sibling.color == :BLACK if (child_sibling.right&.color == :RED && (child_sibling.left.nil? || child_sibling.left&.color == :BLACK)) child_sibling.color = :RED child_sibling.right.color = :BLACK child_sibling.rotate_left child_sibling = left end end child_sibling.color = color @color = :BLACK child_sibling.left.color = :BLACK # if child_sibling.left rotate_right end end |
#color_insert ⇒ Object
:nodoc:
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 |
# File 'lib/tree/red_black/red_black_node.rb', line 466 def color_insert # :nodoc: if parent.nil? @color = :BLACK elsif parent.color == :BLACK return elsif parent_sibling&.color == :RED parent.color = parent_sibling.color = :BLACK grandparent.color = :RED grandparent.color_insert else node = if self == parent.right && parent == grandparent&.left parent.rotate_left.left elsif self == parent.left && parent == grandparent&.right parent.rotate_right.right else self end node.parent.color = :BLACK if node.grandparent node.grandparent.color = :RED if node == node.parent.left node.grandparent.rotate_right else node.grandparent.rotate_left end end end end |
#delete_red_black(value) ⇒ Object
Deletes the given value
from a tree whose root node is self
. If the tree has only one remaining node and its key
attribute matches value
, then the remaining node’s key
attribute is set to nil
but the node itself is not removed. Otherwise, the first node found whose key
matches value
is removed from the tree, and the tree is re-balanced. The root of the balanced tree is returned.
Example
require 'tree/red_black'
root = [*1..10].reduce(Tree::RedBlackNode.new) do |acc, v|
acc.insert_red_black(v)
end
root = [*4..8].reduce(root) do |acc, v|
acc.delete_red_black(v)
end
root.map(&:key) #=> [1, 2, 3, 9, 10]
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 |
# File 'lib/tree/red_black/red_black_node.rb', line 148 def delete_red_black(value) if key.nil? nil elsif value > key right ? right.delete_red_black(value) : nil elsif value < key left ? left.delete_red_black(value) : nil else if left && right node = right.min @key = node.key node.substitute_with_child else substitute_with_child end end end |
#dup ⇒ Object
Returns a deep copy of the tree with root self
, provided that the dup
method for the key
attribute of a node is also a deep copy.
Example
require 'tree/red_black'
root = Tree::RedBlackNode.new({a: 1, b: 2})
root_copy = root.dup
p root.key #=> {:a=>1, :b=>2}
p root.key.delete(:a) #=> 1
p root.key #=> {:b=>2}
p root_copy.key #=> {:a=>1, :b=>2}
405 406 407 408 409 410 411 412 413 414 415 416 |
# File 'lib/tree/red_black/red_black_node.rb', line 405 def dup copy = RedBlackNode.new(key.dup, color) if left copy.left = left.dup copy.left.parent = copy end if right copy.right = right.dup copy.right.parent = copy end copy end |
#grandparent ⇒ Object
:nodoc:
69 70 71 |
# File 'lib/tree/red_black/red_black_node.rb', line 69 def grandparent # :nodoc: parent&.parent end |
#in_order {|_self| ... } ⇒ Object Also known as: each
Returns an enumerator for nodes in the tree with root self
by in-order traversal.
Example
require 'tree/red_black'
shuffled_values = [*1..10].shuffle
root = shuffled_values.reduce(Tree::RedBlackNode.new) do |acc, v|
acc.insert_red_black(v)
end
root.in_order.map(&:key) #=> [1, 2, ..., 10]
381 382 383 384 385 386 387 |
# File 'lib/tree/red_black/red_black_node.rb', line 381 def in_order(&block) return enum_for(:in_order) unless block_given? left.in_order(&block) if left yield self right.in_order(&block) if right end |
#insert_key(value) ⇒ Object
:nodoc:
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 |
# File 'lib/tree/red_black/red_black_node.rb', line 418 def insert_key(value) # :nodoc: if key.nil? @key = value self elsif value >= key if right right.insert_key(value) else @right = RedBlackNode.new(value) @right.parent = self right end else if left left.insert_key(value) else @left = RedBlackNode.new(value) @left.parent = self left end end end |
#insert_red_black(value, allow_duplicates = true) ⇒ Object
Since a Red-Black tree maintains an ordered, Enumerable collection, every value inserted must be Comparable with every other value. Methods each
, map
, select
, find
, sort
, etc., can be applied to a Red-Black tree’s root node to iterate over all nodes in the tree.
Each node yielded by enumeration has a key
attribute to retrieve the value stored in that node. Method each
, in particular, is aliased to in_order
, so that nodes are sorted in ascending order by key
value. Nodes can also be traversed by method pre_order
, e.g., to generate paths in the tree.
Example
require 'tree/red_black'
root = Tree::RedBlackNode.new
p root.key #=> nil
root = root.insert_red_black(0)
p root.key #=> 0
root = root.insert_red_black(1)
p root.key #=> 0
p root.left #=> nil
p root.right.key #=> 1
root = root.insert_red_black(2)
p root.key #=> 1
p root.left.key #=> 0
p root.right.key #=> 2
114 115 116 117 118 119 120 121 122 123 124 125 |
# File 'lib/tree/red_black/red_black_node.rb', line 114 def insert_red_black(value, allow_duplicates = true) node = allow_duplicates ? insert_key(value) : insert_unique_key(value) return nil if node.nil? node.color_insert while node.parent node = node.parent end node end |
#insert_unique_key(value) ⇒ Object
:nodoc:
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 |
# File 'lib/tree/red_black/red_black_node.rb', line 441 def insert_unique_key(value) # :nodoc: if key.nil? @key = value self elsif value > key if right right.insert_unique_key(value) else @right = RedBlackNode.new(value) @right.parent = self right end elsif value < key if left left.insert_unique_key(value) else @left = RedBlackNode.new(value) @left.parent = self left end else nil end end |
#max ⇒ Object
Returns the node whose key
is a maximum in the sub-tree with root self
.
Example
require 'tree/red_black'
root = [*0..10].reduce(Tree::RedBlackNode.new) do |acc, v|
acc.insert_red_black(v)
end
root #=> <Tree::RedBlackNode:0x00..., @key=4, ...>
root.max #=> <Tree::RedBlackNode:0x00..., @key=10, ...>
root.left #=> <Tree::RedBlackNode:0x00..., @key=2, ...>
root.left.max #=> <Tree::RedBlackNode:0x00..., @key=3, ...>
292 293 294 295 296 297 298 |
# File 'lib/tree/red_black/red_black_node.rb', line 292 def max node = self while node.right node = node.right end node end |
#min ⇒ Object
Returns the node whose key
is a minimum in the sub-tree with root self
.
Example
require 'tree/red_black'
root = [*0..10].reduce(Tree::RedBlackNode.new) do |acc, v|
acc.insert_red_black(v)
end
root #=> <Tree::RedBlackNode:0x00..., @key=4, ...>
root.min #=> <Tree::RedBlackNode:0x00..., @key=0, ...>
root.right #=> <Tree::RedBlackNode:0x00..., @key=6, ...>
root.right.min #=> <Tree::RedBlackNode:0x00..., @key=5, ...>
269 270 271 272 273 274 275 |
# File 'lib/tree/red_black/red_black_node.rb', line 269 def min node = self while node.left node = node.left end node end |
#parent_sibling ⇒ Object
:nodoc:
73 74 75 |
# File 'lib/tree/red_black/red_black_node.rb', line 73 def parent_sibling # :nodoc: parent&.sibling end |
#pre_order {|_self| ... } ⇒ Object
Returns an enumerator for nodes in the tree with root self
by pre-order traversal.
Example
require 'tree/red_black'
root = [*1..10].reduce(Tree::RedBlackNode.new) do |acc, v|
acc.insert_red_black(v)
end
root.pre_order.map(&:key) #=> [4, 2, 1, 3, 6, 5, 8, 7, 9, 10]
360 361 362 363 364 365 366 |
# File 'lib/tree/red_black/red_black_node.rb', line 360 def pre_order(&block) return enum_for(:pre_order) unless block_given? yield self left.pre_order(&block) if left right.pre_order(&block) if right end |
#pred ⇒ Object
Returns the node preceding self
, or nil
if no predecessor exists. If duplicate keys are allowed, it’s possible that pred.key == key
.
Example
require 'tree/red_black'
root = [*1..10].reduce(Tree::RedBlackNode.new) do |acc, v|
acc.insert_red_black(v)
end
root.right.right.key #=> 8
root.right.right.pred.key #=> 7
314 315 316 317 318 319 320 321 322 |
# File 'lib/tree/red_black/red_black_node.rb', line 314 def pred return left.max if left node = parent while node && node.key > key node = node.parent end node end |
#rotate_left ⇒ Object
:nodoc:
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 |
# File 'lib/tree/red_black/red_black_node.rb', line 626 def rotate_left # :nodoc: return self if right.nil? root = right root.left.parent = self unless (@right = root.left).nil? if (root.parent = parent) if self == parent.left @parent.left = root else @parent.right = root end end root.left = self @parent = root root end |
#rotate_right ⇒ Object
:nodoc:
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 |
# File 'lib/tree/red_black/red_black_node.rb', line 609 def rotate_right # :nodoc: return self if left.nil? root = left root.right.parent = self unless (@left = root.right).nil? if (root.parent = parent) if self == parent.left @parent.left = root else @parent.right = root end end root.right = self @parent = root root end |
#search(value, ifnone = nil) ⇒ Object
Returns a node whose key
matches value
by binary search. If no match is found, calls non-nil ifnone
, otherwise returns nil
.
Example
require 'tree/red_black'
shuffled_values = [*1..10].shuffle
root = shuffled_values.reduce(Tree::RedBlackNode.new) do |acc, v|
acc.insert_red_black(v)
end
root.search(7) #=> <Tree::RedBlackNode:0x00..., @key=7, ...>
179 180 181 182 183 184 185 186 187 188 189 |
# File 'lib/tree/red_black/red_black_node.rb', line 179 def search(value, ifnone = nil) if key.nil? ifnone && ifnone.call elsif value > key right ? right.search(value, ifnone) : ifnone && ifnone.call elsif value < key left ? left.search(value, ifnone) : ifnone && ifnone.call else self end end |
#sibling ⇒ Object
:nodoc:
65 66 67 |
# File 'lib/tree/red_black/red_black_node.rb', line 65 def sibling # :nodoc: self == parent&.left ? parent&.right : parent&.left end |
#substitute_with_child ⇒ Object
:nodoc:
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 |
# File 'lib/tree/red_black/red_black_node.rb', line 495 def substitute_with_child # :nodoc: if (child = right.nil? ? left : right) child.parent = parent child.color = :BLACK if color == :BLACK end if self == parent&.left parent.left = child parent.color_delete_left if (color == :BLACK && child.nil?) elsif self == parent&.right parent.right = child parent.color_delete_right if (color == :BLACK && child.nil?) end node = parent ? parent : child if node.nil? @key = nil self else while node.parent node = node.parent end node end end |
#succ ⇒ Object
Returns the node succeeding self
, or nil
if no successor exists. If duplicate keys are allowed, it’s possible that succ.key == key
.
Example
require 'tree/red_black'
root = [*1..10].reduce(Tree::RedBlackNode.new) do |acc, v|
acc.insert_red_black(v)
end
root.right.right.key #=> 8
root.right.right.succ.key #=> 9
338 339 340 341 342 343 344 345 346 |
# File 'lib/tree/red_black/red_black_node.rb', line 338 def succ return right.min if right node = parent while node && node.key < key node = node.parent end node end |