3
\$\begingroup\$

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 {
        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 { 
    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(<-ch)
    }
    fmt.Println(Same(tree.New(1), tree.New(1)) == true)
    fmt.Println(Same(tree.New(1), tree.New(2)) == false)
}
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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.

\$\endgroup\$

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.