-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsearch.go
48 lines (40 loc) · 987 Bytes
/
search.go
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
package tree
// SearchStrategy defines a manner in which to search a
// generic tree
type SearchStrategy[T any] func(root *Tree[T]) <-chan *Tree[T]
// DepthFirstStrategy searches root in a depth-first manner.
func DepthFirstStrategy[T any](root *Tree[T]) <-chan *Tree[T] {
out := make(chan *Tree[T])
go func() {
depthFirst(root, out)
close(out)
}()
return out
}
func depthFirst[T any](root *Tree[T], out chan *Tree[T]) {
out <- root
for _, child := range root.children {
depthFirst(child, out)
}
}
// BreadthFirstStrategy searches root in a breadth-first manner.
func BreadthFirstStrategy[T any](root *Tree[T]) <-chan *Tree[T] {
out := make(chan *Tree[T])
go func() {
breadthFirst(root, out)
close(out)
}()
return out
}
func breadthFirst[T any](root *Tree[T], out chan *Tree[T]) {
out <- root
next := root.children
for len(next) != 0 {
var n []*Tree[T]
for i := range next {
out <- next[i]
n = append(n, next[i].children...)
}
next = n
}
}