Debian Codegraph @

trees/redblacktree/redblacktree.go

raw symbols SCIP
1 // Copyright (c) 2015, Emir Pasic. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package redblacktree implements a red-black tree.
6 //
7 // Used by TreeSet and TreeMap.
8 //
9 // Structure is not thread safe.
10 //
11 // References: http://en.wikipedia.org/wiki/Red%E2%80%93black_tree
12 package redblacktree
13
14 import (
15 "cmp"
16 "fmt"
17
18 "github.com/emirpasic/gods/v2/trees"
19 "github.com/emirpasic/gods/v2/utils"
20 )
21
22 // Assert Tree implementation
23 var _ trees.Tree[int] = (*Tree[string, int])(nil)
24
25 type color bool
26
27 const (
28 black, red color = true, false
29 )
30
31 // Tree holds elements of the red-black tree
32 type Tree[K comparable, V any] struct {
33 Root *Node[K, V]
34 size int
35 Comparator utils.Comparator[K]
36 }
37
38 // Node is a single element within the tree
39 type Node[K comparable, V any] struct {
40 Key K
41 Value V
42 color color
43 Left *Node[K, V]
44 Right *Node[K, V]
45 Parent *Node[K, V]
46 }
47
48 // New instantiates a red-black tree with the built-in comparator for K
49 func New[K cmp.Ordered, V any]() *Tree[K, V] {
50 return &Tree[K, V]{Comparator: cmp.Compare[K]}
51 }
52
53 // NewWith instantiates a red-black tree with the custom comparator.
54 func NewWith[K comparable, V any](comparator utils.Comparator[K]) *Tree[K, V] {
55 return &Tree[K, V]{Comparator: comparator}
56 }
57
58 // Put inserts node into the tree.
59 // Key should adhere to the comparator's type assertion, otherwise method panics.
60 func (tree *Tree[K, V]) Put(key K, value V) {
61 var insertedNode *Node[K, V]
62 if tree.Root == nil {
63 // Assert key is of comparator's type for initial tree
64 tree.Comparator(key, key)
65 tree.Root = &Node[K, V]{Key: key, Value: value, color: red}
66 insertedNode = tree.Root
67 } else {
68 node := tree.Root
69 loop := true
70 for loop {
71 compare := tree.Comparator(key, node.Key)
72 switch {
73 case compare == 0:
74 node.Key = key
75 node.Value = value
76 return
77 case compare < 0:
78 if node.Left == nil {
79 node.Left = &Node[K, V]{Key: key, Value: value, color: red}
80 insertedNode = node.Left
81 loop = false
82 } else {
83 node = node.Left
84 }
85 case compare > 0:
86 if node.Right == nil {
87 node.Right = &Node[K, V]{Key: key, Value: value, color: red}
88 insertedNode = node.Right
89 loop = false
90 } else {
91 node = node.Right
92 }
93 }
94 }
95 insertedNode.Parent = node
96 }
97 tree.insertCase1(insertedNode)
98 tree.size++
99 }
100
101 // Get searches the node in the tree by key and returns its value or nil if key is not found in tree.
102 // Second return parameter is true if key was found, otherwise false.
103 // Key should adhere to the comparator's type assertion, otherwise method panics.
104 func (tree *Tree[K, V]) Get(key K) (value V, found bool) {
105 node := tree.lookup(key)
106 if node != nil {
107 return node.Value, true
108 }
109 return value, false
110 }
111
112 // GetNode searches the node in the tree by key and returns its node or nil if key is not found in tree.
113 // Key should adhere to the comparator's type assertion, otherwise method panics.
114 func (tree *Tree[K, V]) GetNode(key K) *Node[K, V] {
115 return tree.lookup(key)
116 }
117
118 // Remove remove the node from the tree by key.
119 // Key should adhere to the comparator's type assertion, otherwise method panics.
120 func (tree *Tree[K, V]) Remove(key K) {
121 var child *Node[K, V]
122 node := tree.lookup(key)
123 if node == nil {
124 return
125 }
126 if node.Left != nil && node.Right != nil {
127 pred := node.Left.maximumNode()
128 node.Key = pred.Key
129 node.Value = pred.Value
130 node = pred
131 }
132 if node.Left == nil || node.Right == nil {
133 if node.Right == nil {
134 child = node.Left
135 } else {
136 child = node.Right
137 }
138 if node.color == black {
139 node.color = nodeColor(child)
140 tree.deleteCase1(node)
141 }
142 tree.replaceNode(node, child)
143 if node.Parent == nil && child != nil {
144 child.color = black
145 }
146 }
147 tree.size--
148 }
149
150 // Empty returns true if tree does not contain any nodes
151 func (tree *Tree[K, V]) Empty() bool {
152 return tree.size == 0
153 }
154
155 // Size returns number of nodes in the tree.
156 func (tree *Tree[K, V]) Size() int {
157 return tree.size
158 }
159
160 // Size returns the number of elements stored in the subtree.
161 // Computed dynamically on each call, i.e. the subtree is traversed to count the number of the nodes.
162 func (node *Node[K, V]) Size() int {
163 if node == nil {
164 return 0
165 }
166 size := 1
167 if node.Left != nil {
168 size += node.Left.Size()
169 }
170 if node.Right != nil {
171 size += node.Right.Size()
172 }
173 return size
174 }
175
176 // Keys returns all keys in-order
177 func (tree *Tree[K, V]) Keys() []K {
178 keys := make([]K, tree.size)
179 it := tree.Iterator()
180 for i := 0; it.Next(); i++ {
181 keys[i] = it.Key()
182 }
183 return keys
184 }
185
186 // Values returns all values in-order based on the key.
187 func (tree *Tree[K, V]) Values() []V {
188 values := make([]V, tree.size)
189 it := tree.Iterator()
190 for i := 0; it.Next(); i++ {
191 values[i] = it.Value()
192 }
193 return values
194 }
195
196 // Left returns the left-most (min) node or nil if tree is empty.
197 func (tree *Tree[K, V]) Left() *Node[K, V] {
198 var parent *Node[K, V]
199 current := tree.Root
200 for current != nil {
201 parent = current
202 current = current.Left
203 }
204 return parent
205 }
206
207 // Right returns the right-most (max) node or nil if tree is empty.
208 func (tree *Tree[K, V]) Right() *Node[K, V] {
209 var parent *Node[K, V]
210 current := tree.Root
211 for current != nil {
212 parent = current
213 current = current.Right
214 }
215 return parent
216 }
217
218 // Floor Finds floor node of the input key, return the floor node or nil if no floor is found.
219 // Second return parameter is true if floor was found, otherwise false.
220 //
221 // Floor node is defined as the largest node that is smaller than or equal to the given node.
222 // A floor node may not be found, either because the tree is empty, or because
223 // all nodes in the tree are larger than the given node.
224 //
225 // Key should adhere to the comparator's type assertion, otherwise method panics.
226 func (tree *Tree[K, V]) Floor(key K) (floor *Node[K, V], found bool) {
227 found = false
228 node := tree.Root
229 for node != nil {
230 compare := tree.Comparator(key, node.Key)
231 switch {
232 case compare == 0:
233 return node, true
234 case compare < 0:
235 node = node.Left
236 case compare > 0:
237 floor, found = node, true
238 node = node.Right
239 }
240 }
241 if found {
242 return floor, true
243 }
244 return nil, false
245 }
246
247 // Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling is found.
248 // Second return parameter is true if ceiling was found, otherwise false.
249 //
250 // Ceiling node is defined as the smallest node that is larger than or equal to the given node.
251 // A ceiling node may not be found, either because the tree is empty, or because
252 // all nodes in the tree are smaller than the given node.
253 //
254 // Key should adhere to the comparator's type assertion, otherwise method panics.
255 func (tree *Tree[K, V]) Ceiling(key K) (ceiling *Node[K, V], found bool) {
256 found = false
257 node := tree.Root
258 for node != nil {
259 compare := tree.Comparator(key, node.Key)
260 switch {
261 case compare == 0:
262 return node, true
263 case compare < 0:
264 ceiling, found = node, true
265 node = node.Left
266 case compare > 0:
267 node = node.Right
268 }
269 }
270 if found {
271 return ceiling, true
272 }
273 return nil, false
274 }
275
276 // Clear removes all nodes from the tree.
277 func (tree *Tree[K, V]) Clear() {
278 tree.Root = nil
279 tree.size = 0
280 }
281
282 // String returns a string representation of container
283 func (tree *Tree[K, V]) String() string {
284 str := "RedBlackTree\n"
285 if !tree.Empty() {
286 output(tree.Root, "", true, &str)
287 }
288 return str
289 }
290
291 func (node *Node[K, V]) String() string {
292 return fmt.Sprintf("%v", node.Key)
293 }
294
295 func output[K comparable, V any](node *Node[K, V], prefix string, isTail bool, str *string) {
296 if node.Right != nil {
297 newPrefix := prefix
298 if isTail {
299 newPrefix += "│ "
300 } else {
301 newPrefix += " "
302 }
303 output(node.Right, newPrefix, false, str)
304 }
305 *str += prefix
306 if isTail {
307 *str += "└── "
308 } else {
309 *str += "┌── "
310 }
311 *str += node.String() + "\n"
312 if node.Left != nil {
313 newPrefix := prefix
314 if isTail {
315 newPrefix += " "
316 } else {
317 newPrefix += "│ "
318 }
319 output(node.Left, newPrefix, true, str)
320 }
321 }
322
323 func (tree *Tree[K, V]) lookup(key K) *Node[K, V] {
324 node := tree.Root
325 for node != nil {
326 compare := tree.Comparator(key, node.Key)
327 switch {
328 case compare == 0:
329 return node
330 case compare < 0:
331 node = node.Left
332 case compare > 0:
333 node = node.Right
334 }
335 }
336 return nil
337 }
338
339 func (node *Node[K, V]) grandparent() *Node[K, V] {
340 if node != nil && node.Parent != nil {
341 return node.Parent.Parent
342 }
343 return nil
344 }
345
346 func (node *Node[K, V]) uncle() *Node[K, V] {
347 if node == nil || node.Parent == nil || node.Parent.Parent == nil {
348 return nil
349 }
350 return node.Parent.sibling()
351 }
352
353 func (node *Node[K, V]) sibling() *Node[K, V] {
354 if node == nil || node.Parent == nil {
355 return nil
356 }
357 if node == node.Parent.Left {
358 return node.Parent.Right
359 }
360 return node.Parent.Left
361 }
362
363 func (tree *Tree[K, V]) rotateLeft(node *Node[K, V]) {
364 right := node.Right
365 tree.replaceNode(node, right)
366 node.Right = right.Left
367 if right.Left != nil {
368 right.Left.Parent = node
369 }
370 right.Left = node
371 node.Parent = right
372 }
373
374 func (tree *Tree[K, V]) rotateRight(node *Node[K, V]) {
375 left := node.Left
376 tree.replaceNode(node, left)
377 node.Left = left.Right
378 if left.Right != nil {
379 left.Right.Parent = node
380 }
381 left.Right = node
382 node.Parent = left
383 }
384
385 func (tree *Tree[K, V]) replaceNode(old *Node[K, V], new *Node[K, V]) {
386 if old.Parent == nil {
387 tree.Root = new
388 } else {
389 if old == old.Parent.Left {
390 old.Parent.Left = new
391 } else {
392 old.Parent.Right = new
393 }
394 }
395 if new != nil {
396 new.Parent = old.Parent
397 }
398 }
399
400 func (tree *Tree[K, V]) insertCase1(node *Node[K, V]) {
401 if node.Parent == nil {
402 node.color = black
403 } else {
404 tree.insertCase2(node)
405 }
406 }
407
408 func (tree *Tree[K, V]) insertCase2(node *Node[K, V]) {
409 if nodeColor(node.Parent) == black {
410 return
411 }
412 tree.insertCase3(node)
413 }
414
415 func (tree *Tree[K, V]) insertCase3(node *Node[K, V]) {
416 uncle := node.uncle()
417 if nodeColor(uncle) == red {
418 node.Parent.color = black
419 uncle.color = black
420 node.grandparent().color = red
421 tree.insertCase1(node.grandparent())
422 } else {
423 tree.insertCase4(node)
424 }
425 }
426
427 func (tree *Tree[K, V]) insertCase4(node *Node[K, V]) {
428 grandparent := node.grandparent()
429 if node == node.Parent.Right && node.Parent == grandparent.Left {
430 tree.rotateLeft(node.Parent)
431 node = node.Left
432 } else if node == node.Parent.Left && node.Parent == grandparent.Right {
433 tree.rotateRight(node.Parent)
434 node = node.Right
435 }
436 tree.insertCase5(node)
437 }
438
439 func (tree *Tree[K, V]) insertCase5(node *Node[K, V]) {
440 node.Parent.color = black
441 grandparent := node.grandparent()
442 grandparent.color = red
443 if node == node.Parent.Left && node.Parent == grandparent.Left {
444 tree.rotateRight(grandparent)
445 } else if node == node.Parent.Right && node.Parent == grandparent.Right {
446 tree.rotateLeft(grandparent)
447 }
448 }
449
450 func (node *Node[K, V]) maximumNode() *Node[K, V] {
451 if node == nil {
452 return nil
453 }
454 for node.Right != nil {
455 node = node.Right
456 }
457 return node
458 }
459
460 func (tree *Tree[K, V]) deleteCase1(node *Node[K, V]) {
461 if node.Parent == nil {
462 return
463 }
464 tree.deleteCase2(node)
465 }
466
467 func (tree *Tree[K, V]) deleteCase2(node *Node[K, V]) {
468 sibling := node.sibling()
469 if nodeColor(sibling) == red {
470 node.Parent.color = red
471 sibling.color = black
472 if node == node.Parent.Left {
473 tree.rotateLeft(node.Parent)
474 } else {
475 tree.rotateRight(node.Parent)
476 }
477 }
478 tree.deleteCase3(node)
479 }
480
481 func (tree *Tree[K, V]) deleteCase3(node *Node[K, V]) {
482 sibling := node.sibling()
483 if nodeColor(node.Parent) == black &&
484 nodeColor(sibling) == black &&
485 nodeColor(sibling.Left) == black &&
486 nodeColor(sibling.Right) == black {
487 sibling.color = red
488 tree.deleteCase1(node.Parent)
489 } else {
490 tree.deleteCase4(node)
491 }
492 }
493
494 func (tree *Tree[K, V]) deleteCase4(node *Node[K, V]) {
495 sibling := node.sibling()
496 if nodeColor(node.Parent) == red &&
497 nodeColor(sibling) == black &&
498 nodeColor(sibling.Left) == black &&
499 nodeColor(sibling.Right) == black {
500 sibling.color = red
501 node.Parent.color = black
502 } else {
503 tree.deleteCase5(node)
504 }
505 }
506
507 func (tree *Tree[K, V]) deleteCase5(node *Node[K, V]) {
508 sibling := node.sibling()
509 if node == node.Parent.Left &&
510 nodeColor(sibling) == black &&
511 nodeColor(sibling.Left) == red &&
512 nodeColor(sibling.Right) == black {
513 sibling.color = red
514 sibling.Left.color = black
515 tree.rotateRight(sibling)
516 } else if node == node.Parent.Right &&
517 nodeColor(sibling) == black &&
518 nodeColor(sibling.Right) == red &&
519 nodeColor(sibling.Left) == black {
520 sibling.color = red
521 sibling.Right.color = black
522 tree.rotateLeft(sibling)
523 }
524 tree.deleteCase6(node)
525 }
526
527 func (tree *Tree[K, V]) deleteCase6(node *Node[K, V]) {
528 sibling := node.sibling()
529 sibling.color = nodeColor(node.Parent)
530 node.Parent.color = black
531 if node == node.Parent.Left && nodeColor(sibling.Right) == red {
532 sibling.Right.color = black
533 tree.rotateLeft(node.Parent)
534 } else if nodeColor(sibling.Left) == red {
535 sibling.Left.color = black
536 tree.rotateRight(node.Parent)
537 }
538 }
539
540 func nodeColor[K comparable, V any](node *Node[K, V]) color {
541 if node == nil {
542 return black
543 }
544 return node.color
545 }