-
Notifications
You must be signed in to change notification settings - Fork 276
/
BSNode.swift
126 lines (83 loc) · 2.69 KB
/
BSNode.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
//
// BSNode.swift
// SwiftStructures
//
// Created by Wayne Bishop on 9/16/17.
// Copyright © 2017 Arbutus Software Inc. All rights reserved.
//
import Foundation
//generic node to be used with binary search trees (BST's)
class BSNode<T>{
var key: T?
var left: BSNode?
var right: BSNode?
var height: Int
init() {
self.height = -1
}
var count: Int {
let left = self.left?.count ?? 0
let right = self.right?.count ?? 0
return left + 1 + right
}
//MARK: Traversal Algorithms
//execute breadth-first search
func BFSTraverse() -> () {
//establish a queue
let bsQueue = Queue<BSNode<T>>()
//queue a starting node
bsQueue.enQueue(self)
while !bsQueue.isEmpty() {
//traverse the next queued node
guard let bitem = bsQueue.deQueue() else {
break
}
print("now traversing item: \(bitem.key!)")
//add decendants to the queue
if let left = bitem.left {
bsQueue.enQueue(left)
}
if let right = bitem.right {
bsQueue.enQueue(right)
}
} //end while
print("bfs traversal complete..")
}
//regular dfs traversal
func DFSTraverse() {
//trivial condition
guard let key = self.key else {
print("no key provided..")
return
}
//process the left side
if self.left != nil {
left?.DFSTraverse()
}
print("...the value is: \(key) - height: \(self.height)..")
//process the right side
if self.right != nil {
right?.DFSTraverse()
}
}
//use dfs with trailing closure to update all values
func DFSTraverse(withFormula formula: (BSNode<T>) -> T) {
//check for trivial condition
guard self.key != nil else {
print("no key provided..")
return
}
//process the left side
if self.left != nil {
left?.DFSTraverse(withFormula: formula)
}
//invoke formula - apply results
let newKey: T = formula(self)
self.key! = newKey
print("...the updated value is: \(self.key!) - height: \(self.height)..")
//process the right side
if self.right != nil {
right?.DFSTraverse(withFormula: formula)
}
}
}