Skip to content

Instantly share code, notes, and snippets.

@shuhei
Created November 11, 2013 05:32
Show Gist options
  • Save shuhei/7408390 to your computer and use it in GitHub Desktop.
Save shuhei/7408390 to your computer and use it in GitHub Desktop.
(A Tour of Go #70) Exercise: Equivalent Binary Trees http://tour.golang.org/#70
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) {
defer close(ch)
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)
}
// 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 {
i1, ok1 := <- ch1
i2, ok2 := <- ch2
if i1 != i2 || ok1 != ok2 { return false }
if !ok1 || !ok2 { break }
}
return true
}
func main() {
fmt.Println("1 vs 1", Same(tree.New(1), tree.New(1)))
fmt.Println("1 vs 2", 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