I'm implementing the Binary Search Tree data structure in Swift. It looks like this:
class BinarySearchTree<Key: Comparable, Value> {
let key: Key
var value: Value
var left, right: BinarySearchTree<Key, Value>?
init(key: Key, value: Value) {
self.key = key
self.value = value
}
// irrelevant methods for constructing a tree
}
To be able to traverse through it using for (key, value) in myTree { }
, BinarySearchTree
has to implement SequenceType
. This is my first attempt:
extension BinarySearchTree: SequenceType {
func generate() -> AnyGenerator<(Key, Value)> {
let leftGenerator = left?.generate()
let rightGenerator = right?.generate()
let (key, value) = (self.key, self.value)
var generatedSelf = false
return AnyGenerator {
if generatedSelf { return rightGenerator?.next() }
else if let next = leftGenerator?.next() { return next }
else {
generatedSelf = true
return (key, value)
}
}
}
}
It works fine, but when I run benchmarks, it's just not as fast as I'd like. Can my traversal algorithm be improved, or is this the fastest way to do it?