Created
February 21, 2017 15:40
-
-
Save daltonclaybrook/8902ca21d5af088bc1c5cf804070b52c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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