Created
June 30, 2018 13:23
-
-
Save digoreis/bb4587659c2842818658e422d88d2024 to your computer and use it in GitHub Desktop.
Sample of BinaryTree with BFS navigation
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 bfs(execute: (T) -> Void) { | |
bfs(node: self, execute: execute) | |
} | |
private func bfs(node: BinaryTree<T>, execute: (T) -> Void) { | |
var queue = [BinaryTree]() | |
queue.append(node) | |
while(queue.count > 0) { | |
let first = queue.removeFirst() | |
switch first { | |
case .node(let left, let value, let right): | |
queue.append(left) | |
queue.append(right) | |
execute(value) | |
break | |
default: | |
continue | |
} | |
} | |
} | |
} | |
let tree: BinaryTree<Int> = .node(.node(.leaf(2),5,.leaf(7)),10,.node(.leaf(11),15,.leaf(30))) | |
tree.bfs { value in | |
print(value) | |
} | |
/********************************* | |
Output: | |
10 | |
5 | |
15 | |
2 | |
7 | |
11 | |
30 | |
*********************************/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment