I'm not sure about this code but it feels ugly to me. It is a solution to this.
package main
import ("golang.org/x/tour/tree"; "fmt"; "reflect"; "sort")
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
if t != nil {
ch <- t.Value
Walk(t.Left, ch)
Walk(t.Right, ch)
}
}
func WalkTest(t *tree.Tree, ch chan int) []int {
go Walk(t, ch)
var testSlice []int
for i := 0; i <10; i++ {
testSlice = append(testSlice, <- ch)
}
return testSlice
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
var t1Slice []int
var t2Slice []int
ch1 := make(chan int, 10)
ch2 := make(chan int, 10)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := 0; i < 10; i++ {
t1Slice = append(t1Slice, <- ch1)
t2Slice = append(t2Slice, <- ch2)
}
sort.Ints(t1Slice); sort.Ints(t2Slice)
return reflect.DeepEqual(t1Slice, t2Slice)
}
func main() {
// Test the walk function
walkTestTree := tree.New(1)
walkTestCh := make(chan int, 10)
walkTest := WalkTest(walkTestTree, walkTestCh)
if len(walkTest) != 10 {
panic("Walk test failed")
}
fmt.Println("Walk test ok!")
// test the Same function
testTree1 := tree.New(1)
testTree2 := tree.New(1)
sameTest := Same(testTree1, testTree2)
if !sameTest {
panic("same test failed")
}
fmt.Println("Same test passed")
aTree := tree.New(1)
bTree := tree.New(1)
fmt.Println(Same(aTree, bTree))
}