I've written a solution for http://tour.golang.org/concurrency/8, which asks for a Walk() function to traverse a randomly generated binary tree, and a Same() function to check if two trees have the same values.

Is this solution is the most efficient? (I think that the Same function is not the most efficient solution, but I don't know how to make it better.)

package main

import "code.google.com/p/go-tour/tree"
import "fmt"

// 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 {
    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 { 
    c1 := make(chan int)
    c2 := make(chan int)
    go Walk(t1,c1) 
    go Walk(t2,c2)
    for z:=0;z<10;z++ {
        if <-c1 != <-c2 {
            return false
    return true

func main() {
    ch := make(chan int)    
    go Walk(tree.New(1), ch)
    for z:= 0; z<10; z++ {
    fmt.Println(Same(tree.New(1), tree.New(1)) == true)
    fmt.Println(Same(tree.New(1), tree.New(2)) == false)

1 Answer 1


In my opinion, you haven't completed the exercise properly, since you have hard-coded the termination after reading 10 values. If a rogue tree.New() produces a larger tree, you should be able to detect it.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.