Skip to content

Instantly share code, notes, and snippets.

@eranation
Created June 4, 2013 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eranation/5707546 to your computer and use it in GitHub Desktop.
Save eranation/5707546 to your computer and use it in GitHub Desktop.
I'm sure there is a better solution, but this is the only thing I came up with that worked (for http://tour.golang.org/#69)
package main
import "code.google.com/p/go-tour/tree"
import "fmt"
import "sort"
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
WalkInternal(t, ch)
close(ch)
}
func WalkInternal(t *tree.Tree, ch chan int) {
if t.Left != nil {
//fmt.Println(t.Value, "going left")
WalkInternal(t.Left, ch)
}
if t.Right != nil {
//fmt.Println(t.Value, "going right")
WalkInternal(t.Right, ch)
}
//fmt.Println(t.Value, "visiting")
ch <- t.Value
//fmt.Println(t.Value, "going up")
}
// 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)
xs := make([]int, 0)
ys := make([]int, 0)
for i := 0; i < 10; i++ {
x:= <-ch1
y:= <-ch2
//fmt.Println(x, y)
xs = append(xs, x)
ys = append(ys, y)
}
sort.Ints(xs)
sort.Ints(ys)
return isEq(xs, ys)
}
func main() {
//ch := make(chan int)
//go Walk(tree.New(1), ch)
//for i := range ch {
// fmt.Println(i)
//}
// for i := 0; i < 10; i++ {
// fmt.Println(<-ch)
// }
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
func isEq(a, b []int) bool {
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment