-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathBinarySearchTree.swift
346 lines (299 loc) · 7.98 KB
/
BinarySearchTree.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
/*
A binary search tree.
Each node stores a value and two children. The left child contains a smaller
value; the right a larger (or equal) value.
This tree allows duplicate elements.
This tree does not automatically balance itself. To make sure it is balanced,
you should insert new values in randomized order, not in sorted order.
*/
public class BinarySearchTree<T: Comparable> {
fileprivate(set) public var value: T
fileprivate(set) public var parent: BinarySearchTree?
fileprivate(set) public var left: BinarySearchTree?
fileprivate(set) public var right: BinarySearchTree?
public init(value: T) {
self.value = value
}
public convenience init(array: [T]) {
precondition(array.count > 0)
self.init(value: array.first!)
for v in array.dropFirst() {
insert(value: v)
}
}
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)
}
}
// MARK: - Adding items
extension BinarySearchTree {
/*
Inserts a new element into the tree. You should only insert elements
at the root, to make to sure this remains a valid binary tree!
Performance: runs in O(h) time, where h is the height of the tree.
*/
public func insert(value: T) {
if value < self.value {
if let left = left {
left.insert(value: value)
} else {
left = BinarySearchTree(value: value)
left?.parent = self
}
} else {
if let right = right {
right.insert(value: value)
} else {
right = BinarySearchTree(value: value)
right?.parent = self
}
}
}
}
// MARK: - Deleting items
extension BinarySearchTree {
/*
Deletes a node from the tree.
Returns the node that has replaced this removed one (or nil if this was a
leaf node). That is primarily useful for when you delete the root node, in
which case the tree gets a new root.
Performance: runs in O(h) time, where h is the height of the tree.
*/
@discardableResult public func remove() -> BinarySearchTree? {
let replacement: BinarySearchTree?
// Replacement for current node can be either biggest one on the left or
// smallest one on the right, whichever is not nil
if let right = right {
replacement = right.minimum()
} else if let left = left {
replacement = left.maximum()
} else {
replacement = nil
}
replacement?.remove()
// Place the replacement on current node's position
replacement?.right = right
replacement?.left = left
right?.parent = replacement
left?.parent = replacement
reconnectParentTo(node:replacement)
// The current node is no longer part of the tree, so clean it up.
parent = nil
left = nil
right = nil
return replacement
}
private func reconnectParentTo(node: BinarySearchTree?) {
if let parent = parent {
if isLeftChild {
parent.left = node
} else {
parent.right = node
}
}
node?.parent = parent
}
}
// MARK: - Searching
extension BinarySearchTree {
/*
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) -> BinarySearchTree? {
var node: BinarySearchTree? = self
while let n = node {
if value < n.value {
node = n.left
} else if value > n.value {
node = n.right
} else {
return node
}
}
return nil
}
/*
// Recursive version of search
public func search(value: T) -> BinarySearchTree? {
if value < self.value {
return left?.search(value)
} else if value > self.value {
return right?.search(value)
} else {
return self // found it!
}
}
*/
public func contains(value: T) -> Bool {
return search(value: value) != nil
}
/*
Returns the leftmost descendent. O(h) time.
*/
public func minimum() -> BinarySearchTree {
var node = self
while let next = node.left {
node = next
}
return node
}
/*
Returns the rightmost descendent. O(h) time.
*/
public func maximum() -> BinarySearchTree {
var node = self
while let next = node.right {
node = next
}
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 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() -> BinarySearchTree<T>? {
if let left = left {
return left.maximum()
} else {
var node = self
while let parent = node.parent {
if parent.value < value { return parent }
node = parent
}
return nil
}
}
/*
Finds the node whose value succeeds our value in sorted order.
*/
public func successor() -> BinarySearchTree<T>? {
if let right = right {
return right.minimum()
} else {
var node = self
while let parent = node.parent {
if parent.value > value { return parent }
node = parent
}
return nil
}
}
}
// MARK: - Traversal
extension BinarySearchTree {
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 BinarySearchTree {
public func isBST(minValue: T, maxValue: T) -> Bool {
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
}
}
// MARK: - Debugging
extension BinarySearchTree: CustomStringConvertible {
public var description: String {
var s = ""
if let left = left {
s += "(\(left.description)) <- "
}
s += "\(value)"
if let right = right {
s += " -> (\(right.description))"
}
return s
}
public func toArray() -> [T] {
return map { $0 }
}
}
//extension BinarySearchTree: CustomDebugStringConvertible {
// public var debugDescription: String {
// var s = ""
// if let left = left {
// s += "(\(left.description)) <- "
// }
// s += "\(value)"
// if let right = right {
// s += " -> (\(right.description))"
// }
// return s
// }
//}