Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
My solution for Go Tour Concurrency Exercise "Equivalent Binary Trees"
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
var walk func(t *tree.Tree, ch chan int)
walk = func(t *tree.Tree, ch chan int) {
if t == nil {
return
}
walk(t.Left, ch)
ch <- t.Value
walk(t.Right, ch)
}
walk(t, ch)
close(ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
c1, c2 := make(chan int), make(chan int)
go Walk(t1, c1)
go Walk(t2, c2)
for v := range c1 {
if v != <-c2 {
return false
}
}
return true
}
func main() {
fmt.Printf("1=1: %v\n", Same(tree.New(1), tree.New(1)))
fmt.Printf("1=2: %v\n", Same(tree.New(1), tree.New(2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.