Created
June 29, 2018 14:07
-
-
Save digoreis/343f04cab2286f514e3ff3edd2f193dc to your computer and use it in GitHub Desktop.
A sample for BinaryTree with Enum.
This file contains hidden or 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 Cocoa | |
indirect enum BinaryTree<T> { | |
case node(BinaryTree, T, BinaryTree) | |
case empty | |
} | |
extension BinaryTree { | |
static func leaf(_ value: T) -> BinaryTree { | |
return .node(.empty,value,.empty) | |
} | |
func dfs(execute: (T) -> Void) { | |
dfs(node: self,execute: execute) | |
} | |
private func dfs(node: BinaryTree, execute: (T) -> Void) { | |
switch node { | |
case .node(let left,let value, let right): | |
dfs(node: left, execute: execute) | |
execute(value) | |
dfs(node: right, execute: execute) | |
break | |
case .empty: | |
return | |
} | |
} | |
} | |
let tree: BinaryTree<Int> = .node(.leaf(5),10,.leaf(89)) | |
tree.dfs { value in | |
print(value) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment