-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorder_example.dart
More file actions
66 lines (53 loc) · 1.46 KB
/
order_example.dart
File metadata and controls
66 lines (53 loc) · 1.46 KB
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
// https://refactoring.guru/design-patterns/iterator/swift/example#example-1
enum IterationType { inOrder, preOrder, postOrder }
class Tree<T> {
T value;
Tree<T>? left;
Tree<T>? right;
Tree(this.value);
List<T> iterator(IterationType type) {
List<T> items = [];
switch (type) {
case IterationType.inOrder:
inOrder(items.add);
case IterationType.preOrder:
preOrder(items.add);
case IterationType.postOrder:
postOrder(items.add);
}
/// Note:
/// AnyIterator is used to hide the type signature of an internal iterator.
return List.from(items);
}
void inOrder(void Function(T) body) {
left?.inOrder(body);
body(value);
right?.inOrder(body);
}
void preOrder(void Function(T) body) {
body(value);
left?.inOrder(body);
right?.inOrder(body);
}
void postOrder(void Function(T) body) {
left?.inOrder(body);
right?.inOrder(body);
body(value);
}
}
void main(List<String> args) {
final tree = Tree(1);
tree.left = Tree(2);
tree.right = Tree(3);
print("Tree traversal: In-order");
clientCode(iterator: tree.iterator(IterationType.inOrder));
print("\nTree traversal: Pre-order");
clientCode(iterator: tree.iterator(IterationType.preOrder));
print("\nTree traversal: Post-order");
clientCode(iterator: tree.iterator(IterationType.postOrder));
}
void clientCode<T>({required List<T> iterator}) {
for (var item in iterator) {
print(item);
}
}