Skip to content

Instantly share code, notes, and snippets.

@Que20
Created December 7, 2020 13:09
Show Gist options
  • Save Que20/caeee1b5981b0f87d980cc22cfe97d31 to your computer and use it in GitHub Desktop.
Save Que20/caeee1b5981b0f87d980cc22cfe97d31 to your computer and use it in GitHub Desktop.
An enum based BinaryTree implementation.
enum BinaryTree<Element> {
case leaf
indirect case node(Element, l: BinaryTree<Element>, r: BinaryTree<Element>)
}
extension BinaryTree {
init(_ value: Element) {
self = .node(value, l: .leaf, r: .leaf)
}
}
extension BinaryTree {
var values: [Element] {
switch self {
case .leaf:
return []
case let .node(el, left, right):
return left.values + [el] + right.values
}
}
func display() -> String {
switch self {
case let .node(el, left, right):
var s = ""
s = " \(el)\n + + \n \(left.display()) \(right.display()))"
return s
default: return ""
}
}
}
let tree: BinaryTree<Int> = .node(5, l: .node(4, l: .leaf, r: .node(3, l: .leaf, r: .leaf)), r: .node(2, l: .leaf, r: .leaf))
print(tree.values)
print(tree.display())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment