Skip to content

Instantly share code, notes, and snippets.

@draftcode
Created May 4, 2014 03:20
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 draftcode/eb4c9cff6dec9096eacf to your computer and use it in GitHub Desktop.
Save draftcode/eb4c9cff6dec9096eacf to your computer and use it in GitHub Desktop.
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
}
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 {
ch1 := make(chan int)
ch2 := make(chan int)
closeWalk := func(t *tree.Tree, ch chan int) {
Walk(t, ch)
close(ch)
}
go closeWalk(t1, ch1)
go closeWalk(t2, ch2)
for {
v1, ok1 := <-ch1
v2, ok2 := <-ch2
if v1 != v2 || ok1 != ok2 {
return false
}
if !ok1 {
break
}
}
return true
}
func main() {
fmt.Println(Same(tree.New(2), tree.New(4)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment