## ~kotrunga/a-tour-of-go

a-tour-of-go/concurrency/3.8_exercise-equivalent-binary-trees.go -rw-r--r-- 1.3 KiB
b3f98925kotrunga remove .DS_Store file 8 months ago
`                                                                                `
```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
78
79
80
81```
```/*
Notes 3.8

Exercise:
https://tour.golang.org/concurrency/7
https://tour.golang.org/concurrency/8

Solution from: https://play.golang.org/p/He5vnWCiyQD
*/

package main

import (
"fmt"

"golang.org/x/tour/tree"
)

func main() {
fmt.Println("Tour of Go Solution - Equivalent Binary Trees\n")

t1 := tree.New(5)
t2 := tree.New(5)
fmt.Println("Tree 1:", t1)
fmt.Println("Tree 2:", t2)
fmt.Println("Are they same? - ", Same(t1, t2))
fmt.Println("------")

t3 := tree.New(2)
t4 := tree.New(3)
fmt.Println("Tree 3:", t3)
fmt.Println("Tree 4:", t4)
fmt.Println("Are they same? - ", Same(t3, t4))
fmt.Println("")
}

func Walker(t *tree.Tree, ch chan int) {
Walk(t, ch)
//close the channel to avoid panic
close(ch)
}

func Walk(t *tree.Tree, ch chan int) {
if t == nil {
return
} else if t.Left == nil {
ch <- t.Value
if t.Right != nil {
Walk(t.Right, ch)
}
return
} else {
Walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
Walk(t.Right, ch)
}
}

func Same(t1, t2 *tree.Tree) bool {
var br bool
done := make(chan bool)
c1 := make(chan int)
c2 := make(chan int)
go Walker(t1, c1)
go Walker(t2, c2)
go func() {
for i := range c1 {
if i == <-c2 {
br = true
} else {
br = false
break
}
}
done <- true
}()
<-done
return br
}
```