Skip to content

Instantly share code, notes, and snippets.

@sri
Last active December 15, 2015 22:59
Show Gist options
  • Save sri/5336453 to your computer and use it in GitHub Desktop.
Save sri/5336453 to your computer and use it in GitHub Desktop.
// sri's solution for http://tour.golang.org/#69
// Exercise: Equivalent Binary Trees
package main
import (
"code.google.com/p/go-tour/tree"
"fmt"
)
func Walk(t *tree.Tree, ch chan int, top bool) {
if t == nil {
return
}
Walk(t.Left, ch, false)
ch <- t.Value
Walk(t.Right, ch, false)
if top {
// not sure how if this is the best way
// to signal eof on channel
close(ch)
}
}
func Same(t1, t2 *tree.Tree) bool {
c1 := make(chan int)
c2 := make(chan int)
go Walk(t1, c1, true)
go Walk(t2, c2, true)
for {
v1, ok1 := <- c1
v2, ok2 := <- c2
if ok1 && ok2 {
if v1 != v2 {
return false
}
} else if !ok1 && !ok2 {
return true
} else {
return false
}
}
return true
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(1))) // true
fmt.Println(Same(tree.New(1), tree.New(2))) // false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment