Source file
tour/solutions/binarytrees_quit.go
1
2
3
4
5
6
7 package main
8
9 import (
10 "fmt"
11
12 "golang.org/x/tour/tree"
13 )
14
15 func walkImpl(t *tree.Tree, ch, quit chan int) {
16 if t == nil {
17 return
18 }
19 walkImpl(t.Left, ch, quit)
20 select {
21 case ch <- t.Value:
22
23 case <-quit:
24 return
25 }
26 walkImpl(t.Right, ch, quit)
27 }
28
29
30
31 func Walk(t *tree.Tree, ch, quit chan int) {
32 walkImpl(t, ch, quit)
33 close(ch)
34 }
35
36
37
38 func Same(t1, t2 *tree.Tree) bool {
39 w1, w2 := make(chan int), make(chan int)
40 quit := make(chan int)
41 defer close(quit)
42
43 go Walk(t1, w1, quit)
44 go Walk(t2, w2, quit)
45
46 for {
47 v1, ok1 := <-w1
48 v2, ok2 := <-w2
49 if !ok1 || !ok2 {
50 return ok1 == ok2
51 }
52 if v1 != v2 {
53 return false
54 }
55 }
56 }
57
58 func main() {
59 fmt.Print("tree.New(1) == tree.New(1): ")
60 if Same(tree.New(1), tree.New(1)) {
61 fmt.Println("PASSED")
62 } else {
63 fmt.Println("FAILED")
64 }
65
66 fmt.Print("tree.New(1) != tree.New(2): ")
67 if !Same(tree.New(1), tree.New(2)) {
68 fmt.Println("PASSED")
69 } else {
70 fmt.Println("FAILED")
71 }
72 }
73
View as plain text