Skip to content

Instantly share code, notes, and snippets.

@daltonclaybrook
Created February 21, 2017 15:40
Show Gist options
  • Save daltonclaybrook/8902ca21d5af088bc1c5cf804070b52c to your computer and use it in GitHub Desktop.
Save daltonclaybrook/8902ca21d5af088bc1c5cf804070b52c to your computer and use it in GitHub Desktop.
class Tree<T: Comparable> {
let root: T
var left: Tree?
var right: Tree?
init(root: T) {
self.root = root
}
func search(value: T) -> Tree? {
guard value != root else { return self }
return value < root ? left?.search(value: value) : right?.search(value: value)
}
func insert(value: T) {
guard value != root else { return }
if value < root {
left?.insert(value: value)
if left == nil {
left = Tree(root: value)
}
} else {
right?.insert(value: value)
if right == nil {
right = Tree(root: value)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment