Skip to content

Instantly share code, notes, and snippets.

@takatoshiono
Last active May 27, 2019 09:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takatoshiono/6835c961892497ac9fd28f7710cf22b1 to your computer and use it in GitHub Desktop.
Save takatoshiono/6835c961892497ac9fd28f7710cf22b1 to your computer and use it in GitHub Desktop.
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)))
}
@takatoshiono
Copy link
Author

takatoshiono commented Sep 6, 2016

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

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

@takatoshiono
Copy link
Author

やった

@mediba-Kitada
Copy link

👍

@dftba-fun
Copy link

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