-
Notifications
You must be signed in to change notification settings - Fork 1
/
exercise-equivalent-binary-trees.go
77 lines (68 loc) · 1.13 KB
/
exercise-equivalent-binary-trees.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
74
75
76
77
package main
import "golang.org/x/tour/tree"
import "fmt"
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
Walk1(t, ch)
close(ch)
}
func Walk1(t *tree.Tree, ch chan int) {
// fmt.Println("Walk1 called")
if t.Left != nil {
Walk1(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
Walk1(t.Right, ch)
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for {
i, morei := <-ch1
j, morej := <-ch2
// fmt.Printf("i = %d, j = %d\n", i, j)
if i != j {
return false
}
if !morei || !morej {
return morei == morej
}
}
}
func main() {
// Walk the tree
ch := make(chan int)
go Walk(tree.New(1), ch)
for {
i, more := <- ch
if !more {
break
}
fmt.Println(i)
}
// Compare trees
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
/*
> go run exercise-equivalent-binary-trees.go
1
2
3
4
5
6
7
8
9
10
true
false
*/