-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBSTree.swift
288 lines (186 loc) · 7.53 KB
/
BSTree.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
//
// BSTree.swift
// SwiftStructures
//
// Created by Wayne Bishop on 9/16/17.
// Copyright © 2017 Arbutus Software Inc. All rights reserved.
//
import Foundation
/*
note: self-balancing binary search tree (BST). Elements are positioned based on their value.
After insertion, model is checked for balance and automatically completes required rotations.
*/
class BSTree<T: Comparable>{
var root = BSNode<T>()
private var elementStack = Stack<BSNode<T>>()
func append(element key: T) {
//initialize root
guard root.key != nil else {
root.key = key
root.height = 0
return
}
//set initial indicator
var current: BSNode<T> = root
while current.key != nil {
//send reference of current item to stack
push(element: ¤t)
//check left side
if key < current.key! {
if current.left != nil {
current = current.left!
}
else {
//create new element
let childToAdd = BSNode<T>()
childToAdd.key = key
childToAdd.height = 0
current.left = childToAdd
break
}
}
//check right side
if key > current.key! {
if current.right != nil {
current = current.right!
}
else {
//create new element
let childToAdd = BSNode<T>()
childToAdd.key = key
childToAdd.height = 0
current.right = childToAdd
break
}
}
} //end while
//calculate height and balance of call stack..
rebalance()
}
//equality test - O(log n)
func contains(_ key: T) -> Bool {
var current: BSNode<T>? = root
while current != nil {
guard let testkey = current?.key else {
return false
}
//test match
if testkey == key {
return true
}
//check left side
if key < testkey {
if current?.left != nil {
current = current?.left
continue
}
else {
return false
}
}
//check right side
if key > testkey {
if current?.right != nil {
current = current?.right
continue
}
else {
return false
}
}
} //end while
return false
}
//stack elements for later processing - memoization
private func push(element: inout BSNode<T>) {
elementStack.push(withKey: element)
print("the stack count is: \(elementStack.count)")
}
//determine height and balance
private func rebalance() {
for _ in stride(from: elementStack.count, through: 1, by: -1) {
//obtain generic stack node - by reference
let current = elementStack.peek()
guard let bsNode: BSNode<T> = current.key else {
print("element reference not found..")
continue
}
setHeight(for: bsNode)
rotate(element: bsNode)
//remove stacked item
elementStack.pop()
}
}
//MARK: Height Methods
private func findHeight(of element: BSNode<T>?) -> Int {
//check empty leaves
guard let bsNode = element else {
return -1
}
return bsNode.height
}
private func setHeight(for element: BSNode<T>) {
//set leaf variables
var elementHeight: Int = 0
//do comparison and calculate height
elementHeight = max(findHeight(of: element.left), findHeight(of: element.right)) + 1
element.height = elementHeight
}
//MARK: Balancing Methods
//determine if the tree is "balanced" - operations on a balanced tree is O(log n)
func isTreeBalanced(for element: BSNode<T>?) -> Bool {
guard element?.key != nil else {
print("no element provided..")
return false
}
//use absolute value to manage right and left imbalances
if (abs(findHeight(of: element?.left) - findHeight(of: element?.right)) <= 1) {
return true
}
else {
return false
}
}
//perform left or right rotation
private func rotate(element: BSNode<T>) {
guard element.key != nil else {
print("cannot rotate: no key provided..")
return
}
if (self.isTreeBalanced(for: element) == true) {
print("node: \(element.key!) already balanced..")
return
}
//create new element
let childToUse = BSNode<T>()
childToUse.height = 0
childToUse.key = element.key
//determine side imbalance
let rightSide = findHeight(of: element.left) - findHeight(of: element.right)
let leftSide = findHeight(of: element.right) - findHeight(of: element.left)
if rightSide > 1 {
print("\n starting right rotation on \(element.key!)..")
//reset the root node
element.key = element.left?.key
element.height = findHeight(of: element.left)
//assign the new right node
element.right = childToUse
//adjust the left node
element.left = element.left?.left
element.left?.height = 0
print("root is: \(element.key!) | left is : \(element.left!.key!) | right is : \(element.right!.key!)..")
}
else if leftSide > 1 {
print("\n starting left rotation on \(element.key!)..")
//reset the root node
element.key = element.right?.key
element.height = findHeight(of: element.right)
//assign the new left node
element.left = childToUse
//adjust the right node
element.right = element.right?.right
element.right?.height = 0
print("root is: \(element.key!) | left is : \(element.left!.key!) | right is : \(element.right!.key!)..")
}
}
}