-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcurrenttreewalk.go
73 lines (67 loc) · 1.37 KB
/
concurrenttreewalk.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
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
package algorithms
import (
"golang.org/x/tour/tree"
)
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func RecursiveConcurrentWalk(t *tree.Tree, ch chan int) {
walk(t, ch)
close(ch)
}
func walk(t *tree.Tree, ch chan int) {
if t.Left != nil {
walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
walk(t.Right, ch)
}
}
// IterativeConcurrentWalk walks the tree t sending all values from the tree to
// the channel ch.
func IterativeConcurrentWalk(t *tree.Tree, ch chan int) {
stack := []*tree.Tree{}
current := t
for {
if current != nil {
stack = append(stack, current)
current = current.Left
} else if len(stack) > 0 {
current, stack = pop(stack)
ch <- current.Value
current = current.Right
} else {
break
}
}
close(ch)
}
func pop(stack []*tree.Tree) (*tree.Tree, []*tree.Tree) {
n := len(stack) - 1
t := stack[n]
stack[n] = nil
return t, stack[:n]
}
func MorrisIterativeConcurrentWalk(t *tree.Tree, ch chan int) {
current := t
for current != nil {
if current.Left == nil {
ch <- current.Value
current = current.Right
} else {
pre := current.Left
for pre.Right != nil && pre.Right != current {
pre = pre.Right
}
if pre.Right == nil {
pre.Right = current
current = current.Left
} else {
pre.Right = nil
ch <- current.Value
current = current.Right
}
}
}
close(ch)
}