Skip to content

Instantly share code, notes, and snippets.

@jackfarrington
Last active August 29, 2015 14:26
Show Gist options
  • Save jackfarrington/b932519ae333861d3d10 to your computer and use it in GitHub Desktop.
Save jackfarrington/b932519ae333861d3d10 to your computer and use it in GitHub Desktop.
Exercise: Equivalent Binary Trees (https://tour.golang.org/concurrency/8)
package main
import "fmt"
import "golang.org/x/tour/tree"
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
var walk func(t *tree.Tree)
walk = func(t * tree.Tree) {
if t == nil { return }
walk(t.Left)
ch <- t.Value
walk(t.Right)
}
walk(t)
close(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)
go Walk(t1, ch1)
go Walk(t2, ch2)
for v1 := range ch1 {
v2, ok := <- ch2
if !ok || v1 != v2 { return false }
}
if _, ok := <- ch2; ok { return false }
return true
}
func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
for v := range ch {
fmt.Println(v)
}
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment