-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trees_LevelOrderTraversal
93 lines (72 loc) · 1.67 KB
/
Trees_LevelOrderTraversal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import UIKit
struct Queue<Element> {
var elements: [Element] = []
mutating func enqueue(_ value: Element) -> Bool {
elements.append(value)
return true
}
var isEmpty: Bool {
return elements.isEmpty
}
mutating func dequeue() -> Element? {
return isEmpty ? nil : elements.removeFirst()
}
}
class TreeNode<T> {
var value: T
var children: [TreeNode] = []
init(_ value: T) {
self.value = value
}
func add(_ child: TreeNode) {
self.children.append(child)
}
}
extension TreeNode {
func forEachLevelOrder(_ visit: (TreeNode) -> Void) {
visit(self) //call root node
var queue = Queue<TreeNode>()
children.forEach {
queue.enqueue($0)
}
while let node = queue.dequeue() {
visit(node)
node.children.forEach {
queue.enqueue($0)
}
}
}
}
/*
Beverages
/ \
Hot Cold
/ \ / \
Tea Coffee Soda Milk
*/
let beverages = TreeNode<String>("Beverages")
let hot = TreeNode<String>("Hot")
let cold = TreeNode<String>("Cold")
beverages.add(hot)
beverages.add(cold)
let tea = TreeNode<String>("Tea")
let coffee = TreeNode<String>("Coffee")
hot.add(tea)
hot.add(coffee)
let soda = TreeNode<String>("Soda")
let milk = TreeNode<String>("Milk")
cold.add(soda)
cold.add(milk)
beverages.forEachLevelOrder {
print($0.value) // level order traversal
}
/*
Output printed:
Beverages
Hot
Cold
Tea
Coffee
Soda
Milk
*/