Skip to content

Instantly share code, notes, and snippets.

@sorah
Created May 2, 2014 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorah/bbc59707a853928a6c63 to your computer and use it in GitHub Desktop.
Save sorah/bbc59707a853928a6c63 to your computer and use it in GitHub Desktop.
// http://tour.golang.org/#72
package main
import "code.google.com/p/go-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) {
if t == nil {
return
}
ch <- t.Value
Walk(t.Left, ch)
Walk(t.Right, 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)
qch := make(chan bool)
counts := make(map[int]int)
go Workout(t1, ch1)
go Workout(t2, ch2)
go Counter(counts, ch1, qch)
go Counter(counts, ch2, qch)
_ = <-qch
_ = <-qch
for _, v := range counts {
if v != 2 {
return false
}
}
return true
}
func Workout(t *tree.Tree, ch chan int) {
Walk(t, ch)
close(ch)
}
func Counter(counts map[int]int, ch chan int, qch chan bool) {
for v := range ch {
//fmt.Println("2: ", v)
counts[v] += 1
}
qch <- true
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(1)))
}
@draftcode
Copy link

こんなかんじ?

https://gist.github.com/draftcode/eb4c9cff6dec9096eacf

Workoutぐらいの関数だったらinlineにしてしまうかなぁ

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