I am trying to solve equivalent binary trees exercise on go tour. Here is what I did;
package main
import \"tour/tree\"
import \"fmt\"
// Walk walks the tr
You should avoid to let opened channels unattended or a thread can be waiting forever and never ending.
package main
import "code.google.com/p/go-tour/tree"
import "fmt"
func WalkRecurse(t *tree.Tree, ch chan int) {
if t == nil {
return
}
WalkRecurse(t.Left, ch)
ch <- t.Value
WalkRecurse(t.Right, ch)
}
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
WalkRecurse(t, ch)
close(ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
var ch1, ch2 chan int = make(chan int), make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
ret := true
for {
v1, ok1 := <- ch1
v2, ok2 := <- ch2
if ok1 != ok2 {
ret = false
}
if ok1 && (v1 != v2) {
ret = false
}
if !ok1 && !ok2 {
break
}
}
return ret
}
func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
for v := range ch {
fmt.Print(v, " ")
}
fmt.Println()
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}