Skip to content

Instantly share code, notes, and snippets.

@fanzeyi
Created September 27, 2012 19:19
Show Gist options
  • Save fanzeyi/3795881 to your computer and use it in GitHub Desktop.
Save fanzeyi/3795881 to your computer and use it in GitHub Desktop.
My answser for `A Tour of Go` Part III
package main
import "fmt"
import "code.google.com/p/go-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) {
_walk(t, ch)
close(ch)
}
func _walk(t *tree.Tree, ch chan int) {
//fmt.Println(t.Value)
if(t.Left != nil) {
_walk(t.Left, ch)
}
ch <- t.Value
if(t.Right != nil) {
_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, 100)
ch2 := make(chan int, 100)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := range ch1 {
if(i != <- ch2) {
return false;
}
}
return true
}
func main() {
t1 := tree.New(1)
t2 := tree.New(2)
fmt.Println(Same(t1, t1))
fmt.Println(Same(tree.New(1),tree.New(1)))
fmt.Println(Same(t1, t2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment