forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SplayTree.swift
557 lines (449 loc) · 14.9 KB
/
SplayTree.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
/*
* Splay Tree
*
* Based on Binary Search Tree Implementation written by Nicolas Ameghino and Matthijs Hollemans for Swift Algorithms Club
* https://github.com/raywenderlich/swift-algorithm-club/blob/master/Binary%20Search%20Tree
* And extended for the specifics of a Splay Tree by Barbara Martina Rodeker
*
*/
/**
Represent the 3 possible operations (combinations of rotations) that
could be performed during the Splay phase in Splay Trees
- zigZag Left child of a right child OR right child of a left child
- zigZig Left child of a left child OR right child of a right child
- zig Only 1 parent and that parent is the root
*/
public enum SplayOperation {
case zigZag
case zigZig
case zig
/**
Splay the given node up to the root of the tree
- Parameters:
- node SplayTree node to move up to the root
*/
public static func splay<T: Comparable>(node: Node<T>) {
while (node.parent != nil) {
operation(forNode: node).apply(onNode: node)
}
}
/**
Compares the node and its parent and determine
if the rotations should be performed in a zigZag, zigZig or zig case.
- Parmeters:
- forNode SplayTree node to be checked
- Returns
- Operation Case zigZag - zigZig - zig
*/
public static func operation<T>(forNode node: Node<T>) -> SplayOperation {
if let parent = node.parent, let _ = parent.parent {
if (node.isLeftChild && parent.isRightChild) || (node.isRightChild && parent.isLeftChild) {
return .zigZag
}
return .zigZig
}
return .zig
}
/**
Applies the rotation associated to the case
Modifying the splay tree and briging the received node further to the top of the tree
- Parameters:
- onNode Node to splay up. Should be alwayas the node that needs to be splayed, neither its parent neither it's grandparent
*/
public func apply<T: Comparable>(onNode node: Node<T>) {
switch self {
case .zigZag:
assert(node.parent != nil && node.parent!.parent != nil, "Should be at least 2 nodes up in the tree")
rotate(child: node, parent: node.parent!)
rotate(child: node, parent: node.parent!)
case .zigZig:
assert(node.parent != nil && node.parent!.parent != nil, "Should be at least 2 nodes up in the tree")
rotate(child: node.parent!, parent: node.parent!.parent!)
rotate(child: node, parent: node.parent!)
case .zig:
assert(node.parent != nil && node.parent!.parent == nil, "There should be a parent which is the root")
rotate(child: node, parent: node.parent!)
}
}
/**
Performs a single rotation from a node to its parent
re-arranging the children properly
*/
public func rotate<T: Comparable>(child: Node<T>, parent: Node<T>) {
assert(child.parent != nil && child.parent!.value == parent.value, "Parent and child.parent should match here")
var grandchildToMode: Node<T>?
if child.isLeftChild {
grandchildToMode = child.right
parent.left = grandchildToMode
grandchildToMode?.parent = parent
let grandParent = parent.parent
child.parent = grandParent
if parent.isLeftChild {
grandParent?.left = child
} else {
grandParent?.right = child
}
child.right = parent
parent.parent = child
} else {
grandchildToMode = child.left
parent.right = grandchildToMode
grandchildToMode?.parent = parent
let grandParent = parent.parent
child.parent = grandParent
if parent.isLeftChild {
grandParent?.left = child
} else {
grandParent?.right = child
}
child.left = parent
parent.parent = child
}
}
}
public class Node<T: Comparable> {
fileprivate(set) public var value: T?
fileprivate(set) public var parent: Node<T>?
fileprivate(set) public var left: Node<T>?
fileprivate(set) public var right: Node<T>?
init(value: T) {
self.value = value
}
public var isRoot: Bool {
return parent == nil
}
public var isLeaf: Bool {
return left == nil && right == nil
}
public var isLeftChild: Bool {
return parent?.left === self
}
public var isRightChild: Bool {
return parent?.right === self
}
public var hasLeftChild: Bool {
return left != nil
}
public var hasRightChild: Bool {
return right != nil
}
public var hasAnyChild: Bool {
return hasLeftChild || hasRightChild
}
public var hasBothChildren: Bool {
return hasLeftChild && hasRightChild
}
/* How many nodes are in this subtree. Performance: O(n). */
public var count: Int {
return (left?.count ?? 0) + 1 + (right?.count ?? 0)
}
}
public class SplayTree<T: Comparable> {
internal var root: Node<T>?
var value: T? {
return root?.value
}
//MARK: - Initializer
public init(value: T) {
self.root = Node(value:value)
}
public func insert(value: T) {
if let root = root {
self.root = root.insert(value: value)
} else {
root = Node(value: value)
}
}
public func remove(value: T) {
root = root?.remove(value: value)
}
public func search(value: T) -> Node<T>? {
root = root?.search(value: value)
return root
}
public func minimum() -> Node<T>? {
root = root?.minimum(splayed: true)
return root
}
public func maximum() -> Node<T>? {
root = root?.maximum(splayed: true)
return root
}
}
// MARK: - Adding items
extension Node {
/*
Inserts a new element into the node tree.
- Parameters:
- value T value to be inserted. Will be splayed to the root position
- Returns:
- Node inserted
*/
public func insert(value: T) -> Node {
if let selfValue = self.value {
if value < selfValue {
if let left = left {
return left.insert(value: value)
} else {
left = Node(value: value)
left?.parent = self
if let left = left {
SplayOperation.splay(node: left)
return left
}
}
} else {
if let right = right {
return right.insert(value: value)
} else {
right = Node(value: value)
right?.parent = self
if let right = right {
SplayOperation.splay(node: right)
return right
}
}
}
}
return self
}
}
// MARK: - Deleting items
extension Node {
/*
Deletes the given node from the nodes tree.
Return the new tree generated by the removal.
The removed node (not necessarily the one containing the value), will be splayed to the root.
- Parameters:
- value To be removed
- Returns:
- Node Resulting from the deletion and the splaying of the removed node
*/
fileprivate func remove(value: T) -> Node<T>? {
guard let target = search(value: value) else { return self }
if let left = target.left, let right = target.right {
let largestOfLeftChild = left.maximum()
left.parent = nil
right.parent = nil
SplayOperation.splay(node: largestOfLeftChild)
largestOfLeftChild.right = right
return largestOfLeftChild
} else if let left = target.left {
replace(node: target, with: left)
return left
} else if let right = target.right {
replace(node: target, with: right)
return right
} else {
return nil
}
}
private func replace(node: Node<T>, with newNode: Node<T>?) {
guard let sourceParent = sourceNode.parent else { return }
if sourceNode.isLeftChild {
sourceParent.left = newNode
} else {
sourceParent.right = newNode
}
newNode?.parent = sourceParent
}
}
// MARK: - Searching
extension Node {
/*
Finds the "highest" node with the specified value.
Performance: runs in O(h) time, where h is the height of the tree.
*/
public func search(value: T) -> Node<T>? {
var node: Node? = self
var nodeParent: Node? = self
while case let n? = node, n.value != nil {
if value < n.value! {
if n.left != nil { nodeParent = n.left }
node = n.left
} else if value > n.value! {
node = n.right
if n.right != nil { nodeParent = n.right }
} else {
break
}
}
if let node = node {
SplayOperation.splay(node: node)
return node
} else if let nodeParent = nodeParent {
SplayOperation.splay(node: nodeParent)
return nodeParent
}
return nil
}
public func contains(value: T) -> Bool {
return search(value: value) != nil
}
/*
Returns the leftmost descendent. O(h) time.
*/
public func minimum(splayed: Bool = false) -> Node<T> {
var node = self
while case let next? = node.left {
node = next
}
if splayed == true {
SplayOperation.splay(node: node)
}
return node
}
/*
Returns the rightmost descendent. O(h) time.
*/
public func maximum(splayed: Bool = false) -> Node<T> {
var node = self
while case let next? = node.right {
node = next
}
if splayed == true {
SplayOperation.splay(node: node)
}
return node
}
/*
Calculates the depth of this node, i.e. the distance to the root.
Takes O(h) time.
*/
public func depth() -> Int {
var node = self
var edges = 0
while case let parent? = node.parent {
node = parent
edges += 1
}
return edges
}
/*
Calculates the height of this node, i.e. the distance to the lowest leaf.
Since this looks at all children of this node, performance is O(n).
*/
public func height() -> Int {
if isLeaf {
return 0
} else {
return 1 + max(left?.height() ?? 0, right?.height() ?? 0)
}
}
/*
Finds the node whose value precedes our value in sorted order.
*/
public func predecessor() -> Node<T>? {
if let left = left {
return left.maximum()
} else {
var node = self
while case let parent? = node.parent, parent.value != nil, value != nil {
if parent.value! < value! { return parent }
node = parent
}
return nil
}
}
/*
Finds the node whose value succeeds our value in sorted order.
*/
public func successor() -> Node<T>? {
if let right = right {
return right.minimum()
} else {
var node = self
while case let parent? = node.parent, parent.value != nil , value != nil {
if parent.value! > value! { return parent }
node = parent
}
return nil
}
}
}
// MARK: - Traversal
extension Node {
public func traverseInOrder(process: (T) -> Void) {
left?.traverseInOrder(process: process)
process(value!)
right?.traverseInOrder(process: process)
}
public func traversePreOrder(process: (T) -> Void) {
process(value!)
left?.traversePreOrder(process: process)
right?.traversePreOrder(process: process)
}
public func traversePostOrder(process: (T) -> Void) {
left?.traversePostOrder(process: process)
right?.traversePostOrder(process: process)
process(value!)
}
/*
Performs an in-order traversal and collects the results in an array.
*/
public func map(formula: (T) -> T) -> [T] {
var a = [T]()
if let left = left { a += left.map(formula: formula) }
a.append(formula(value!))
if let right = right { a += right.map(formula: formula) }
return a
}
}
/*
Is this binary tree a valid binary search tree?
*/
extension Node {
public func isBST(minValue: T, maxValue: T) -> Bool {
if let value = value {
if value < minValue || value > maxValue { return false }
let leftBST = left?.isBST(minValue: minValue, maxValue: value) ?? true
let rightBST = right?.isBST(minValue: value, maxValue: maxValue) ?? true
return leftBST && rightBST
}
return false
}
}
// MARK: - Debugging
extension Node: CustomStringConvertible {
public var description: String {
var s = ""
if let left = left {
s += "left: (\(left.description)) <- "
}
if let v = value {
s += "\(v)"
}
if let right = right {
s += " -> (right: \(right.description))"
}
return s
}
}
extension SplayTree: CustomStringConvertible {
public var description: String {
return root?.description ?? "Empty tree"
}
}
extension Node: CustomDebugStringConvertible {
public var debugDescription: String {
var s = "value: \(value)"
if let parent = parent, let v = parent.value {
s += ", parent: \(v)"
}
if let left = left {
s += ", left = [" + left.debugDescription + "]"
}
if let right = right {
s += ", right = [" + right.debugDescription + "]"
}
return s
}
public func toArray() -> [T] {
return map { $0 }
}
}
extension SplayTree: CustomDebugStringConvertible {
public var debugDescription: String {
return root?.debugDescription ?? "Empty tree"
}
}