Created
January 27, 2016 08:27
-
-
Save erikolsson/c7678146029b38c51598 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
import UIKit | |
indirect enum Tree<Element : Comparable> { | |
case Empty | |
case Node(Element, Tree<Element>, Tree<Element>) | |
init() { | |
self = .Empty | |
} | |
init(value: Element, left: Tree<Element> = .Empty, right: Tree<Element> = .Empty) { | |
self = .Node(value, left, right) | |
} | |
} | |
func insertElement<T>(root: Tree<T>, _ x: T) -> Tree<T> { | |
guard case let .Node(y, left, right) = root else { | |
return Tree(value: x) | |
} | |
if x < y { return Tree(value: y, left: insertElement(left, x), right: right) } | |
if x > y { return Tree(value: y, left: left, right: insertElement(right, x)) } | |
return root | |
} | |
extension Tree { | |
func insert(element: Element) -> Tree { | |
guard case let .Node(y, left, right) = insertElement(self, element) else { | |
fatalError("Empty!") | |
} | |
return .Node(y, left, right) | |
} | |
func contains(element: Element) -> Bool { | |
guard case let .Node(value, left, right) = self else { | |
return false | |
} | |
if element < value { return left.contains(element) } | |
if element > value { return right.contains(element) } | |
return true | |
} | |
} | |
var t: Tree<String> = .Empty | |
t = t.insert("hello") | |
t = t.insert("hello 2") | |
t.contains("hello") | |
t.contains("hello 3") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment