-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trees_Search.swift
111 lines (83 loc) · 2.24 KB
/
Trees_Search.swift
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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 where T: Equatable {
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) //call node
node.children.forEach {
queue.enqueue($0)
}
}
}
func search(_ value: T) -> TreeNode? {
var result: TreeNode?
forEachLevelOrder { node in
if node.value == value {
result = node
}
}
return result
}
}
/*
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)
//Test 1:
if let searchResult = beverages.search("Soda") {
print(searchResult.value) // Soda
}
//Test 2:
if let searchResult = beverages.search("Custard") {
print(searchResult.value) //
}
else {
print("Custard not found") // Custard not found
}
//Test 3:
if let searchResult = beverages.search("Milk") {
print(searchResult.value) // Milk
}