Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A Tour of Go: Exercise Equivalent Binary Trees, https://go-tour-jp.appspot.com/concurrency/8
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) {
var walker func(t *tree.Tree)
walker = func(t *tree.Tree) {
if t == nil {
return
}
walker(t.Left)
ch <- t.Value
walker(t.Right)
}
walker(t)
close(ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1, ch2 := make(chan int), make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for value := range ch1 {
if value != <-ch2 {
return false
}
}
return true
}
func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
for i := 0; i < 10; i++ {
fmt.Println(<-ch)
}
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
Owner
takatoshiono commented Sep 6, 2016 edited

いくつか回答をググって学んだこと

  • Walkを再帰的に呼ぶのではなくfuncを新しく作ってそれを再帰的に呼ぶ。そうするとclose(ch)できる
  • Sameで比較するときは配列に全部入れる必要なくて、1つずつ値を取り出して比較していけばよい
  • mainでSameの戻り値を確かめるのに単にPrintlnすればよい
Owner

やった

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment