-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTreeNode.swift
198 lines (171 loc) · 5.77 KB
/
TreeNode.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
//
// TreeNode.swift
//
// Advent of Code Tools
//
import Collections
public class TreeNode<Value> {
public let value: Value
public private(set) var children: [TreeNode]
public private(set) var parent: TreeNode?
public var count: Int {
1 + children.reduce(0) { $0 + $1.count }
}
public init(_ value: Value, children: [TreeNode] = []) {
self.value = value
self.parent = nil
self.children = children
children.forEach { $0.parent = self }
}
public func add(_ node: TreeNode) {
children.append(node)
node.parent = self
}
public func delete() {
guard
let parent = self.parent,
let index = parent.children.firstIndex(where: { $0 === self })
else {
return
}
parent.children.remove(at: index)
self.parent = nil
}
/// recursively visit all nodes in the tree, depth-first
/// - Parameters:
/// - closure: called for every node in the tree
/// - node: the visited node
/// - level: the depth of the node (root is at 0)
public func visitAll(_ closure: (_ node: TreeNode, _ level: Int) -> Void) {
visitAll(at: 0, closure)
}
private func visitAll(at level: Int, _ closure: (TreeNode, Int) -> Void) {
closure(self, level)
children.forEach { $0.visitAll(at: level + 1, closure) }
}
public func reduce<Result>(_ initialResult: Result,
_ nextPartialResult: (Result, Value) -> Result
) -> Result {
var result = nextPartialResult(initialResult, value)
children.forEach {
result = $0.reduce(result, nextPartialResult)
}
return result
}
public func reduce<Result>(into result: Result,
_ updateAccumulatingResult: (inout Result, Value) -> Void
) -> Result {
var result = result
updateAccumulatingResult(&result, value)
children.forEach {
result = $0.reduce(into: result, updateAccumulatingResult)
}
return result
}
}
// MARK: - DFS recursive
extension TreeNode {
/// Perform a recursive depth-first search for the node where `predicate` returns true
/// - Parameter predicate: a closure to check if the `value` of a node is a match
/// - Returns: the first node that satisfies `predicate`, or `nil` if no such node is found
public func first(where predicate: (Value) -> Bool) -> TreeNode? {
if predicate(value) {
return self
}
for child in children {
if let found = child.first(where: predicate) {
return found
}
}
return nil
}
/// Perform a recursive depth-first search for all nodes where `predicate` returns true
public func filter(where predicate: (Value) -> Bool) -> [TreeNode] {
var result = [TreeNode]()
filter(where: predicate, result: &result)
return result
}
private func filter(where predicate: (Value) -> Bool, result: inout [TreeNode]) {
if predicate(value) {
result.append(self)
}
children.forEach {
$0.filter(where: predicate, result: &result)
}
}
}
// MARK: - DFS iterative
extension TreeNode {
public func firstIterative(where predicate: (Value) -> Bool) -> TreeNode? {
var list = Deque([self])
while let current = list.popFirst() {
if predicate(current.value) {
return current
}
list.prepend(contentsOf: current.children)
}
return nil
}
public func filterIterative(where predicate: (Value) -> Bool) -> [TreeNode] {
var list = Deque([self])
var result = [TreeNode]()
while let current = list.popFirst() {
if predicate(current.value) {
result.append(current)
}
list.prepend(contentsOf: current.children)
}
return result
}
}
// MARK: - BFS
extension TreeNode {
/// Perform a breadth-first search for the node where `predicate` returns true
/// - Parameter predicate: a closure to check if the `value` of a node is a match
/// - Returns: the first node that satisfies `predicate`, or `nil` if no such node is found
public func breadthFirstSearch(_ predicate: (Value) -> Bool) -> TreeNode? {
var queue = Deque([self])
while let current = queue.popFirst() {
if predicate(current.value) {
return current
}
queue.append(contentsOf: current.children)
}
return nil
}
public func breadthFirstSearchAll(_ predicate: (Value) -> Bool) -> [TreeNode] {
var result = [TreeNode]()
var queue = Deque([self])
while let current = queue.popFirst() {
if predicate(current.value) {
result.append(current)
}
queue.append(contentsOf: current.children)
}
return result
}
}
extension TreeNode: Equatable where Value: Equatable {
public static func == (lhs: TreeNode, rhs: TreeNode) -> Bool {
lhs.value == rhs.value && lhs.children == rhs.children
}
}
extension TreeNode: Hashable where Value: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
hasher.combine(children)
}
}
extension TreeNode where Value: CustomStringConvertible {
public func print() {
Self.printTree(at: self, level: 0)
}
private static func printTree(at node: TreeNode, level: Int) {
let indent = String(repeating: " ", count: level * 2)
Swift.print(indent, terminator: "")
Swift.print(node.value)
for child in node.children {
printTree(at: child, level: level + 1)
}
}
}