Skip to content

Instantly share code, notes, and snippets.

@yuuki
Created May 4, 2014 08:59
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 yuuki/3d089821b759edcc2497 to your computer and use it in GitHub Desktop.
Save yuuki/3d089821b759edcc2497 to your computer and use it in GitHub Desktop.
package main
import (
"code.google.com/p/go-tour/tree"
"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
}
Walk(t.Left, ch)
ch <- t.Value
Walk(t.Right, ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
c1, c2 := make(chan int), make(chan int)
go func() {
Walk(t1, c1)
close(c1)
}()
go func() {
Walk(t1, c2)
close(c2)
}()
for {
x, ok1 := <-c1
y, ok2 := <-c2
if !ok1 || !ok2 {
return ok1 == ok2
}
if x != y {
return false
}
}
return false
}
func main() {
t := tree.New(1)
ch := make(chan int)
go func() {
Walk(t, ch)
close(ch)
}()
for i := range ch {
fmt.Println(i)
}
if Same(tree.New(1), tree.New(1)) {
fmt.Println("Same!")
}
if Same(tree.New(1), tree.New(2)) {
fmt.Println("Not Same!")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment