-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVLTree.swift
463 lines (393 loc) · 12.3 KB
/
AVLTree.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
// The MIT License (MIT)
// Copyright (c) 2016 Mike Taghavi (mitghi[at]me.com)
// 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.
public class TreeNode<Key: Comparable, Payload> {
public typealias Node = TreeNode<Key, Payload>
var payload: Payload? // Value held by the node
fileprivate var key: Key // Node's name
internal var leftChild: Node?
internal var rightChild: Node?
fileprivate var height: Int
weak fileprivate var parent: Node?
public init(key: Key, payload: Payload?, leftChild: Node?, rightChild: Node?, parent: Node?, height: Int) {
self.key = key
self.payload = payload
self.leftChild = leftChild
self.rightChild = rightChild
self.parent = parent
self.height = height
self.leftChild?.parent = self
self.rightChild?.parent = self
}
public convenience init(key: Key, payload: Payload?) {
self.init(key: key, payload: payload, leftChild: nil, rightChild: nil, parent: nil, height: 1)
}
public convenience init(key: Key) {
self.init(key: key, payload: nil)
}
var isRoot: Bool {
return parent == nil
}
var isLeaf: Bool {
return rightChild == nil && leftChild == nil
}
var isLeftChild: Bool {
return parent?.leftChild === self
}
var isRightChild: Bool {
return parent?.rightChild === self
}
var hasLeftChild: Bool {
return leftChild != nil
}
var hasRightChild: Bool {
return rightChild != nil
}
var hasAnyChild: Bool {
return leftChild != nil || rightChild != nil
}
var hasBothChildren: Bool {
return leftChild != nil && rightChild != nil
}
}
// MARK: - The AVL tree
open class AVLTree<Key: Comparable, Payload> {
public typealias Node = TreeNode<Key, Payload>
fileprivate(set) var root: Node?
fileprivate(set) var size = 0
public init() { }
}
// MARK: - Searching
extension TreeNode {
public func minimum() -> TreeNode? {
return leftChild?.minimum() ?? self
}
public func maximum() -> TreeNode? {
return rightChild?.maximum() ?? self
}
}
extension AVLTree {
subscript(key: Key) -> Payload? {
get { return search(input: key) }
set { insert(key: key, payload: newValue) }
}
public func search(input: Key) -> Payload? {
return search(key: input, node: root)?.payload
}
fileprivate func search(key: Key, node: Node?) -> Node? {
if let node = node {
if key == node.key {
return node
} else if key < node.key {
return search(key: key, node: node.leftChild)
} else {
return search(key: key, node: node.rightChild)
}
}
return nil
}
}
// MARK: - Inserting new items
extension AVLTree {
public func insert(key: Key, payload: Payload? = nil) {
if let root = root {
insert(input: key, payload: payload, node: root)
} else {
root = Node(key: key, payload: payload)
}
size += 1
}
private func insert(input: Key, payload: Payload?, node: Node) {
if input < node.key {
if let child = node.leftChild {
insert(input: input, payload: payload, node: child)
} else {
let child = Node(key: input, payload: payload, leftChild: nil, rightChild: nil, parent: node, height: 1)
node.leftChild = child
balance(node: child)
}
} else if input != node.key {
if let child = node.rightChild {
insert(input: input, payload: payload, node: child)
} else {
let child = Node(key: input, payload: payload, leftChild: nil, rightChild: nil, parent: node, height: 1)
node.rightChild = child
balance(node: child)
}
}
}
}
// MARK: - Balancing tree
extension AVLTree {
fileprivate func updateHeightUpwards(node: Node?) {
if let node = node {
let lHeight = node.leftChild?.height ?? 0
let rHeight = node.rightChild?.height ?? 0
node.height = max(lHeight, rHeight) + 1
updateHeightUpwards(node: node.parent)
}
}
fileprivate func lrDifference(node: Node?) -> Int {
let lHeight = node?.leftChild?.height ?? 0
let rHeight = node?.rightChild?.height ?? 0
return lHeight - rHeight
}
fileprivate func balance(node: Node?) {
guard let node = node else {
return
}
updateHeightUpwards(node: node.leftChild)
updateHeightUpwards(node: node.rightChild)
var nodes = [Node?](repeating: nil, count: 3)
var subtrees = [Node?](repeating: nil, count: 4)
let nodeParent = node.parent
let lrFactor = lrDifference(node: node)
if lrFactor > 1 {
// left-left or left-right
if lrDifference(node: node.leftChild) > 0 {
// left-left
nodes[0] = node
nodes[2] = node.leftChild
nodes[1] = nodes[2]?.leftChild
subtrees[0] = nodes[1]?.leftChild
subtrees[1] = nodes[1]?.rightChild
subtrees[2] = nodes[2]?.rightChild
subtrees[3] = nodes[0]?.rightChild
} else {
// left-right
nodes[0] = node
nodes[1] = node.leftChild
nodes[2] = nodes[1]?.rightChild
subtrees[0] = nodes[1]?.leftChild
subtrees[1] = nodes[2]?.leftChild
subtrees[2] = nodes[2]?.rightChild
subtrees[3] = nodes[0]?.rightChild
}
} else if lrFactor < -1 {
// right-left or right-right
if lrDifference(node: node.rightChild) < 0 {
// right-right
nodes[1] = node
nodes[2] = node.rightChild
nodes[0] = nodes[2]?.rightChild
subtrees[0] = nodes[1]?.leftChild
subtrees[1] = nodes[2]?.leftChild
subtrees[2] = nodes[0]?.leftChild
subtrees[3] = nodes[0]?.rightChild
} else {
// right-left
nodes[1] = node
nodes[0] = node.rightChild
nodes[2] = nodes[0]?.leftChild
subtrees[0] = nodes[1]?.leftChild
subtrees[1] = nodes[2]?.leftChild
subtrees[2] = nodes[2]?.rightChild
subtrees[3] = nodes[0]?.rightChild
}
} else {
// Don't need to balance 'node', go for parent
balance(node: node.parent)
return
}
// nodes[2] is always the head
if node.isRoot {
root = nodes[2]
root?.parent = nil
} else if node.isLeftChild {
nodeParent?.leftChild = nodes[2]
nodes[2]?.parent = nodeParent
} else if node.isRightChild {
nodeParent?.rightChild = nodes[2]
nodes[2]?.parent = nodeParent
}
nodes[2]?.leftChild = nodes[1]
nodes[1]?.parent = nodes[2]
nodes[2]?.rightChild = nodes[0]
nodes[0]?.parent = nodes[2]
nodes[1]?.leftChild = subtrees[0]
subtrees[0]?.parent = nodes[1]
nodes[1]?.rightChild = subtrees[1]
subtrees[1]?.parent = nodes[1]
nodes[0]?.leftChild = subtrees[2]
subtrees[2]?.parent = nodes[0]
nodes[0]?.rightChild = subtrees[3]
subtrees[3]?.parent = nodes[0]
updateHeightUpwards(node: nodes[1]) // Update height from left
updateHeightUpwards(node: nodes[0]) // Update height from right
balance(node: nodes[2]?.parent)
}
}
// MARK: - Displaying tree
extension AVLTree {
fileprivate func display(node: Node?, level: Int) {
if let node = node {
display(node: node.rightChild, level: level + 1)
print("")
if node.isRoot {
print("Root -> ", terminator: "")
}
for _ in 0..<level {
print(" ", terminator: "")
}
print("(\(node.key):\(node.height))", terminator: "")
display(node: node.leftChild, level: level + 1)
}
}
public func display(node: Node) {
display(node: node, level: 0)
print("")
}
public func inorder(node: Node?) -> String {
var output = ""
if let node = node {
output = "\(inorder(node: node.leftChild)) \(print("\(node.key) ")) \(inorder(node: node.rightChild))"
}
return output
}
public func preorder(node: Node?) -> String {
var output = ""
if let node = node {
output = "\(preorder(node: node.leftChild)) \(print("\(node.key) ")) \(preorder(node: node.rightChild))"
}
return output
}
public func postorder(node: Node?) -> String {
var output = ""
if let node = node {
output = "\(postorder(node: node.leftChild)) \(print("\(node.key) ")) \(postorder(node: node.rightChild))"
}
return output
}
}
// MARK: - Delete node
extension AVLTree {
public func delete(key: Key) {
if size == 1 {
root = nil
size -= 1
} else if let node = search(key: key, node: root) {
delete(node: node)
size -= 1
}
}
private func delete(node: Node) {
if node.isLeaf {
// Just remove and balance up
if let parent = node.parent {
guard node.isLeftChild || node.isRightChild else {
// just in case
fatalError("Error: tree is invalid.")
}
if node.isLeftChild {
parent.leftChild = nil
} else if node.isRightChild {
parent.rightChild = nil
}
balance(node: parent)
} else {
// at root
root = nil
}
} else {
// Handle stem cases
if let replacement = node.leftChild?.maximum(), replacement !== node {
node.key = replacement.key
node.payload = replacement.payload
delete(node: replacement)
} else if let replacement = node.rightChild?.minimum(), replacement !== node {
node.key = replacement.key
node.payload = replacement.payload
delete(node: replacement)
}
}
}
}
// MARK: - Advanced Stuff
extension AVLTree {
public func doInOrder(node: Node?, _ completion: (Node) -> Void) {
if let node = node {
doInOrder(node: node.leftChild) { lnode in
completion(lnode)
}
completion(node)
doInOrder(node: node.rightChild) { rnode in
completion(rnode)
}
}
}
public func doInPreOrder(node: Node?, _ completion: (Node) -> Void) {
if let node = node {
completion(node)
doInPreOrder(node: node.leftChild) { lnode in
completion(lnode)
}
doInPreOrder(node: node.rightChild) { rnode in
completion(rnode)
}
}
}
public func doInPostOrder(node: Node?, _ completion: (Node) -> Void) {
if let node = node {
doInPostOrder(node: node.leftChild) { lnode in
completion(lnode)
}
doInPostOrder(node: node.rightChild) { rnode in
completion(rnode)
}
completion(node)
}
}
}
// MARK: - Debugging
extension TreeNode: CustomDebugStringConvertible {
public var debugDescription: String {
var s = "key: \(key), payload: \(payload), height: \(height)"
if let parent = parent {
s += ", parent: \(parent.key)"
}
if let left = leftChild {
s += ", left = [" + left.debugDescription + "]"
}
if let right = rightChild {
s += ", right = [" + right.debugDescription + "]"
}
return s
}
}
extension AVLTree: CustomDebugStringConvertible {
public var debugDescription: String {
return root?.debugDescription ?? "[]"
}
}
extension TreeNode: CustomStringConvertible {
public var description: String {
var s = ""
if let left = leftChild {
s += "(\(left.description)) <- "
}
s += "\(key)"
if let right = rightChild {
s += " -> (\(right.description))"
}
return s
}
}
extension AVLTree: CustomStringConvertible {
public var description: String {
return root?.description ?? "[]"
}
}