Skip to content

Instantly share code, notes, and snippets.

@royling
Last active December 16, 2015 09:08
Show Gist options
  • Save royling/8f6fa4ff9b20594a3cf8 to your computer and use it in GitHub Desktop.
Save royling/8f6fa4ff9b20594a3cf8 to your computer and use it in GitHub Desktop.
A function to check whether two binary trees store the same sequence is quite complex in most languages. We'll use Go's concurrency and channels to write a simple solution.
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) {
_walk(t, ch)
close(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, ch2 := make(chan int), make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for {
v1, ok1 := <- ch1
v2, ok2 := <- ch2
if v1 != v2 || ok1 != ok2 {
return false
}
if !ok1 { // end
break
}
}
return true
}
func main() {
// Test Walk
ch := make(chan int)
go Walk(tree.New(1), ch)
for i := 0; i < 10; i++ {
fmt.Println(<-ch)
}
// Test Same
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