I am trying to solve equivalent binary trees exercise on go tour. Here is what I did;
package main
import "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.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
Walk(t.Right, ch)
}
}
// 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)
for k := range ch1 {
select {
case g := <-ch2:
if k != g {
return false
}
default:
break
}
}
return true
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
However, I couldn’t find out how to signal if any no more elements left in trees. I can’t use close(ch) on Walk() because it makes the channel close before all values are sent (because of recursion.) Can anyone lend me a hand here?
You could use close() if your Walk function doesn’t recurse on itself. i.e. Walk would just do:
Where walkRecurse is more or less your current Walk function, but recursing on walkRecurse.
(or you rewrite Walk to be iterative – which, granted, is more hassle)
With this approach, your Same() function have to learn that the channels was closed, which is done with the channel receive of the form
And take proper action when
ok1andok2are different, or when they’re bothfalseAnother way, but probably not in the spirit of the exercise, is to count the number of nodes in the tree:
You’ll have to implement the countTreeNodes() function, which should count the number of nodes in a *Tree