Skip to content

Commit 2912d4d

Browse files
author
Nico Ameghino
committed
Added a basic implementation of an unbalanced btree using enums
1 parent de971c5 commit 2912d4d

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Trees/Tree.swift

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import Foundation
2+
3+
enum Tree<T: Comparable> {
4+
indirect case Node(Tree, T, Tree)
5+
case Leaf(T)
6+
case Empty
7+
8+
func insert(new: T) -> Tree {
9+
switch self {
10+
case .Leaf(let value):
11+
if new < value {
12+
return .Node(.Leaf(new), value, .Empty)
13+
} else {
14+
return .Node(.Empty, value, .Leaf(new))
15+
}
16+
case .Empty:
17+
return .Leaf(new)
18+
case .Node(let left, let value, let right):
19+
if new < value {
20+
return .Node(left.insert(new), value, right)
21+
} else {
22+
return .Node(left, value, right.insert(new))
23+
}
24+
}
25+
}
26+
27+
var height: Int {
28+
switch self {
29+
case .Empty: return 0
30+
case .Leaf(_): return 1
31+
case .Node(let left, _, let right): return 1 + max(left.height, right.height)
32+
}
33+
}
34+
}
35+
36+
extension Tree: CustomDebugStringConvertible {
37+
var debugDescription: String {
38+
switch self {
39+
case .Empty: return "<X>"
40+
case .Leaf(let v): return "\(v)"
41+
case .Node(let left, let value, let right): return "(\(left.debugDescription) <- \(value) -> \(right.debugDescription))"
42+
}
43+
}
44+
}
45+

0 commit comments

Comments
 (0)