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)
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jan 8, 2015 at 12:41
\$\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.

answered Jan 8, 2015 at 17:37
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.