forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RedBlackTree.swift
795 lines (720 loc) · 24.2 KB
/
RedBlackTree.swift
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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
//Copyright (c) 2016 Matthijs Hollemans and contributors
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
import Foundation
private enum RBTreeColor {
case red
case black
}
private enum RotationDirection {
case left
case right
}
// MARK: - RBNode
public class RBTreeNode<T: Comparable>: Equatable {
public typealias RBNode = RBTreeNode<T>
fileprivate var color: RBTreeColor = .black
fileprivate var key: T?
var leftChild: RBNode?
var rightChild: RBNode?
fileprivate weak var parent: RBNode?
public init(key: T?, leftChild: RBNode?, rightChild: RBNode?, parent: RBNode?) {
self.key = key
self.leftChild = leftChild
self.rightChild = rightChild
self.parent = parent
self.leftChild?.parent = self
self.rightChild?.parent = self
}
public convenience init(key: T?) {
self.init(key: key, leftChild: RBNode(), rightChild: RBNode(), parent: RBNode())
}
// For initialising the nullLeaf
public convenience init() {
self.init(key: nil, leftChild: nil, rightChild: nil, parent: nil)
self.color = .black
}
var isRoot: Bool {
return parent == nil
}
var isLeaf: Bool {
return rightChild == nil && leftChild == nil
}
var isNullLeaf: Bool {
return key == nil && isLeaf && color == .black
}
var isLeftChild: Bool {
return parent?.leftChild === self
}
var isRightChild: Bool {
return parent?.rightChild === self
}
var grandparent: RBNode? {
return parent?.parent
}
var sibling: RBNode? {
if isLeftChild {
return parent?.rightChild
} else {
return parent?.leftChild
}
}
var uncle: RBNode? {
return parent?.sibling
}
}
// MARK: - RedBlackTree
public class RedBlackTree<T: Comparable> {
public typealias RBNode = RBTreeNode<T>
fileprivate(set) var root: RBNode
fileprivate(set) var size = 0
fileprivate let nullLeaf = RBNode()
fileprivate let allowDuplicateNode: Bool
public init(_ allowDuplicateNode: Bool = false) {
root = nullLeaf
self.allowDuplicateNode = allowDuplicateNode
}
}
// MARK: - Size
extension RedBlackTree {
public func count() -> Int {
return size
}
public func isEmpty() -> Bool {
return size == 0
}
public func allElements() -> [T] {
var nodes: [T] = []
getAllElements(node: root, nodes: &nodes)
return nodes
}
private func getAllElements(node: RBTreeNode<T>, nodes: inout [T]) {
guard !node.isNullLeaf else {
return
}
if let left = node.leftChild {
getAllElements(node: left, nodes: &nodes)
}
if let key = node.key {
nodes.append(key)
}
if let right = node.rightChild {
getAllElements(node: right, nodes: &nodes)
}
}
}
// MARK: - Equatable protocol
extension RBTreeNode {
static public func == <T>(lhs: RBTreeNode<T>, rhs: RBTreeNode<T>) -> Bool {
return lhs.key == rhs.key
}
}
// MARK: - Finding a nodes successor
extension RBTreeNode {
/*
* Returns the inorder successor node of a node
* The successor is a node with the next larger key value of the current node
*/
public func getSuccessor() -> RBNode? {
// If node has right child: successor min of this right tree
if let rightChild = self.rightChild {
if !rightChild.isNullLeaf {
return rightChild.minimum()
}
}
// Else go upward until node left child
var currentNode = self
var parent = currentNode.parent
while currentNode.isRightChild {
if let parent = parent {
currentNode = parent
}
parent = currentNode.parent
}
return parent
}
}
// MARK: - Searching
extension RBTreeNode {
/*
* Returns the node with the minimum key of the current subtree
*/
public func minimum() -> RBNode? {
if let leftChild = leftChild {
if !leftChild.isNullLeaf {
return leftChild.minimum()
}
return self
}
return self
}
/*
* Returns the node with the maximum key of the current subtree
*/
public func maximum() -> RBNode? {
if let rightChild = rightChild {
if !rightChild.isNullLeaf {
return rightChild.maximum()
}
return self
}
return self
}
}
extension RedBlackTree {
/*
* Returns the node with the given key |input| if existing
*/
public func search(input: T) -> RBNode? {
return search(key: input, node: root)
}
/*
* Returns the node with given |key| in subtree of |node|
*/
fileprivate func search(key: T, node: RBNode?) -> RBNode? {
// If node nil -> key not found
guard let node = node else {
return nil
}
// If node is nullLeaf == semantically same as if nil
if !node.isNullLeaf {
if let nodeKey = node.key {
// Node found
if key == nodeKey {
return node
} else if key < nodeKey {
return search(key: key, node: node.leftChild)
} else {
return search(key: key, node: node.rightChild)
}
}
}
return nil
}
}
// MARK: - Finding maximum and minimum value
extension RedBlackTree {
/*
* Returns the minimum key value of the whole tree
*/
public func minValue() -> T? {
guard let minNode = root.minimum() else {
return nil
}
return minNode.key
}
/*
* Returns the maximum key value of the whole tree
*/
public func maxValue() -> T? {
guard let maxNode = root.maximum() else {
return nil
}
return maxNode.key
}
}
// MARK: - Inserting new nodes
extension RedBlackTree {
/*
* Insert a node with key |key| into the tree
* 1. Perform normal insert operation as in a binary search tree
* 2. Fix red-black properties
* Runntime: O(log n)
*/
public func insert(key: T) {
// If key must be unique and find the key already existed, quit
if search(input: key) != nil && !allowDuplicateNode {
return
}
if root.isNullLeaf {
root = RBNode(key: key)
} else {
insert(input: RBNode(key: key), node: root)
}
size += 1
}
/*
* Nearly identical insert operation as in a binary search tree
* Differences: All nil pointers are replaced by the nullLeaf, we color the inserted node red,
* after inserting we call insertFixup to maintain the red-black properties
*/
private func insert(input: RBNode, node: RBNode) {
guard let inputKey = input.key, let nodeKey = node.key else {
return
}
if inputKey < nodeKey {
guard let child = node.leftChild else {
addAsLeftChild(child: input, parent: node)
return
}
if child.isNullLeaf {
addAsLeftChild(child: input, parent: node)
} else {
insert(input: input, node: child)
}
} else {
guard let child = node.rightChild else {
addAsRightChild(child: input, parent: node)
return
}
if child.isNullLeaf {
addAsRightChild(child: input, parent: node)
} else {
insert(input: input, node: child)
}
}
}
private func addAsLeftChild(child: RBNode, parent: RBNode) {
parent.leftChild = child
child.parent = parent
child.color = .red
insertFixup(node: child)
}
private func addAsRightChild(child: RBNode, parent: RBNode) {
parent.rightChild = child
child.parent = parent
child.color = .red
insertFixup(node: child)
}
/*
* Fixes possible violations of the red-black property after insertion
* Only violation of red-black properties occurs at inserted node |z| and z.parent
* We have 3 distinct cases: case 1, 2a and 2b
* - case 1: may repeat, but only h/2 steps, where h is the height of the tree
* - case 2a -> case 2b -> red-black tree
* - case 2b -> red-black tree
*/
private func insertFixup(node z: RBNode) {
if !z.isNullLeaf {
guard let parentZ = z.parent else {
return
}
// If both |z| and his parent are red -> violation of red-black property -> need to fix it
if parentZ.color == .red {
guard let uncle = z.uncle else {
return
}
// Case 1: Uncle red -> recolor + move z
if uncle.color == .red {
parentZ.color = .black
uncle.color = .black
if let grandparentZ = parentZ.parent {
grandparentZ.color = .red
// Move z to grandparent and check again
insertFixup(node: grandparentZ)
}
}
// Case 2: Uncle black
else {
var zNew = z
// Case 2.a: z right child -> rotate
if parentZ.isLeftChild && z.isRightChild {
zNew = parentZ
leftRotate(node: zNew)
} else if parentZ.isRightChild && z.isLeftChild {
zNew = parentZ
rightRotate(node: zNew)
}
// Case 2.b: z left child -> recolor + rotate
zNew.parent?.color = .black
if let grandparentZnew = zNew.grandparent {
grandparentZnew.color = .red
if z.isLeftChild {
rightRotate(node: grandparentZnew)
} else {
leftRotate(node: grandparentZnew)
}
// We have a valid red-black-tree
}
}
}
}
root.color = .black
}
}
// MARK: - Deleting a node
extension RedBlackTree {
/*
* Delete a node with key |key| from the tree
* 1. Perform standard delete operation as in a binary search tree
* 2. Fix red-black properties
* Runntime: O(log n)
*/
public func delete(key: T) {
if size == 1 {
root = nullLeaf
size -= 1
} else if let node = search(key: key, node: root) {
if !node.isNullLeaf {
delete(node: node)
size -= 1
}
}
}
/*
* Nearly identical delete operation as in a binary search tree
* Differences: All nil pointers are replaced by the nullLeaf,
* after deleting we call insertFixup to maintain the red-black properties if the delted node was
* black (as if it was red -> no violation of red-black properties)
*/
private func delete(node z: RBNode) {
var nodeY = RBNode()
var nodeX = RBNode()
if let leftChild = z.leftChild, let rightChild = z.rightChild {
if leftChild.isNullLeaf || rightChild.isNullLeaf {
nodeY = z
} else {
if let successor = z.getSuccessor() {
nodeY = successor
}
}
}
if let leftChild = nodeY.leftChild {
if !leftChild.isNullLeaf {
nodeX = leftChild
} else if let rightChild = nodeY.rightChild {
nodeX = rightChild
}
}
nodeX.parent = nodeY.parent
if let parentY = nodeY.parent {
// Should never be the case, as parent of root = nil
if parentY.isNullLeaf {
root = nodeX
} else {
if nodeY.isLeftChild {
parentY.leftChild = nodeX
} else {
parentY.rightChild = nodeX
}
}
} else {
root = nodeX
}
if nodeY != z {
z.key = nodeY.key
}
// If sliced out node was red -> nothing to do as red-black-property holds
// If it was black -> fix red-black-property
if nodeY.color == .black {
deleteFixup(node: nodeX)
}
}
/*
* Fixes possible violations of the red-black property after deletion
* We have w distinct cases: only case 2 may repeat, but only h many steps, where h is the height
* of the tree
* - case 1 -> case 2 -> red-black tree
* case 1 -> case 3 -> case 4 -> red-black tree
* case 1 -> case 4 -> red-black tree
* - case 3 -> case 4 -> red-black tree
* - case 4 -> red-black tree
*/
private func deleteFixup(node x: RBNode) {
var xTmp = x
if !x.isRoot && x.color == .black {
guard var sibling = x.sibling else {
return
}
// Case 1: Sibling of x is red
if sibling.color == .red {
// Recolor
sibling.color = .black
if let parentX = x.parent {
parentX.color = .red
// Rotation
if x.isLeftChild {
leftRotate(node: parentX)
} else {
rightRotate(node: parentX)
}
// Update sibling
if let sibl = x.sibling {
sibling = sibl
}
}
}
// Case 2: Sibling is black with two black children
if sibling.leftChild?.color == .black && sibling.rightChild?.color == .black {
// Recolor
sibling.color = .red
// Move fake black unit upwards
if let parentX = x.parent {
deleteFixup(node: parentX)
}
// We have a valid red-black-tree
} else {
// Case 3: a. Sibling black with one black child to the right
if x.isLeftChild && sibling.rightChild?.color == .black {
// Recolor
sibling.leftChild?.color = .black
sibling.color = .red
// Rotate
rightRotate(node: sibling)
// Update sibling of x
if let sibl = x.sibling {
sibling = sibl
}
}
// Still case 3: b. One black child to the left
else if x.isRightChild && sibling.leftChild?.color == .black {
// Recolor
sibling.rightChild?.color = .black
sibling.color = .red
// Rotate
leftRotate(node: sibling)
// Update sibling of x
if let sibl = x.sibling {
sibling = sibl
}
}
// Case 4: Sibling is black with red right child
// Recolor
if let parentX = x.parent {
sibling.color = parentX.color
parentX.color = .black
// a. x left and sibling with red right child
if x.isLeftChild {
sibling.rightChild?.color = .black
// Rotate
leftRotate(node: parentX)
}
// b. x right and sibling with red left child
else {
sibling.leftChild?.color = .black
//Rotate
rightRotate(node: parentX)
}
// We have a valid red-black-tree
xTmp = root
}
}
}
xTmp.color = .black
}
}
// MARK: - Rotation
extension RedBlackTree {
/*
* Left rotation around node x
* Assumes that x.rightChild y is not a nullLeaf, rotates around the link from x to y,
* makes y the new root of the subtree with x as y's left child and y's left child as x's right
* child, where n = a node, [n] = a subtree
* | |
* x y
* / \ ~> / \
* [A] y x [C]
* / \ / \
* [B] [C] [A] [B]
*/
fileprivate func leftRotate(node x: RBNode) {
rotate(node: x, direction: .left)
}
/*
* Right rotation around node y
* Assumes that y.leftChild x is not a nullLeaf, rotates around the link from y to x,
* makes x the new root of the subtree with y as x's right child and x's right child as y's left
* child, where n = a node, [n] = a subtree
* | |
* x y
* / \ <~ / \
* [A] y x [C]
* / \ / \
* [B] [C] [A] [B]
*/
fileprivate func rightRotate(node x: RBNode) {
rotate(node: x, direction: .right)
}
/*
* Rotation around a node x
* Is a local operation preserving the binary-search-tree property that only exchanges pointers.
* Runntime: O(1)
*/
private func rotate(node x: RBNode, direction: RotationDirection) {
var nodeY: RBNode? = RBNode()
// Set |nodeY| and turn |nodeY|'s left/right subtree into |x|'s right/left subtree
switch direction {
case .left:
nodeY = x.rightChild
x.rightChild = nodeY?.leftChild
x.rightChild?.parent = x
case .right:
nodeY = x.leftChild
x.leftChild = nodeY?.rightChild
x.leftChild?.parent = x
}
// Link |x|'s parent to nodeY
nodeY?.parent = x.parent
if x.isRoot {
if let node = nodeY {
root = node
}
} else if x.isLeftChild {
x.parent?.leftChild = nodeY
} else if x.isRightChild {
x.parent?.rightChild = nodeY
}
// Put |x| on |nodeY|'s left
switch direction {
case .left:
nodeY?.leftChild = x
case .right:
nodeY?.rightChild = x
}
x.parent = nodeY
}
}
// MARK: - Verify
extension RedBlackTree {
/*
* Verifies that the existing tree fulfills all red-black properties
* Returns true if the tree is a valid red-black tree, false otherwise
*/
public func verify() -> Bool {
if root.isNullLeaf {
print("The tree is empty")
return true
}
return property2() && property4() && property5()
}
// Property 1: Every node is either red or black -> fullfilled through setting node.color of type
// RBTreeColor
// Property 2: The root is black
private func property2() -> Bool {
if root.color == .red {
print("Property-Error: Root is red")
return false
}
return true
}
// Property 3: Every nullLeaf is black -> fullfilled through initialising nullLeafs with color = black
// Property 4: If a node is red, then both its children are black
private func property4() -> Bool {
return property4(node: root)
}
private func property4(node: RBNode) -> Bool {
if node.isNullLeaf {
return true
}
if let leftChild = node.leftChild, let rightChild = node.rightChild {
if node.color == .red {
if !leftChild.isNullLeaf && leftChild.color == .red {
print("Property-Error: Red node with key \(String(describing: node.key)) has red left child")
return false
}
if !rightChild.isNullLeaf && rightChild.color == .red {
print("Property-Error: Red node with key \(String(describing: node.key)) has red right child")
return false
}
}
return property4(node: leftChild) && property4(node: rightChild)
}
return false
}
// Property 5: For each node, all paths from the node to descendant leaves contain the same number
// of black nodes (same blackheight)
private func property5() -> Bool {
if property5(node: root) == -1 {
return false
} else {
return true
}
}
private func property5(node: RBNode) -> Int {
if node.isNullLeaf {
return 0
}
guard let leftChild = node.leftChild, let rightChild = node.rightChild else {
return -1
}
let left = property5(node: leftChild)
let right = property5(node: rightChild)
if left == -1 || right == -1 {
return -1
} else if left == right {
let addedHeight = node.color == .black ? 1 : 0
return left + addedHeight
} else {
print("Property-Error: Black height violated at node with key \(String(describing: node.key))")
return -1
}
}
}
// MARK: - Debugging
extension RBTreeNode: CustomDebugStringConvertible {
public var debugDescription: String {
var s = ""
if isNullLeaf {
s = "nullLeaf"
} else {
if let key = key {
s = "key: \(key)"
} else {
s = "key: nil"
}
if let parent = parent {
s += ", parent: \(String(describing: parent.key))"
}
if let left = leftChild {
s += ", left = [" + left.debugDescription + "]"
}
if let right = rightChild {
s += ", right = [" + right.debugDescription + "]"
}
s += ", color = \(color)"
}
return s
}
}
extension RedBlackTree: CustomDebugStringConvertible {
public var debugDescription: String {
return root.debugDescription
}
}
extension RBTreeNode: CustomStringConvertible {
public var description: String {
var s = ""
if isNullLeaf {
s += "nullLeaf"
} else {
if let left = leftChild {
s += "(\(left.description)) <- "
}
if let key = key {
s += "\(key)"
} else {
s += "nil"
}
s += ", \(color)"
if let right = rightChild {
s += " -> (\(right.description))"
}
}
return s
}
}
extension RedBlackTree: CustomStringConvertible {
public var description: String {
if root.isNullLeaf {
return "[]"
} else {
return root.description
}
}
}