Skip to content

Instantly share code, notes, and snippets.

@yfktn
Created April 19, 2018 08:14
Show Gist options
  • Save yfktn/89583a2770531c97999847ced8e14249 to your computer and use it in GitHub Desktop.
Save yfktn/89583a2770531c97999847ced8e14249 to your computer and use it in GitHub Desktop.
Answer to Go Playground Exercise
// https://tour.golang.org/concurrency/8
package main
import "golang.org/x/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) {
// we need to close channel, so it need to call separately
recursiveWalk(t, ch)
close(ch) // to stop the range
}
// visit every leaf from the left
func recursiveWalk(t *tree.Tree, ch chan int) {
if t != nil {
recursiveWalk(t.Left, ch) // go for Left leaf first!
// send value to channel
ch <- t.Value
recursiveWalk(t.Right, ch)
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
el1 := make(chan int) // channel for t1
el2 := make(chan int) // channel for t2
go Walk(t1, el1) // walk into t1
go Walk(t2, el2) // walk into t2
for {
// wait for channel notif
v1,ok1 := <-el1
v2,ok2 := <-el2
if ok1 && ok2 {
if v1 != v2 {
return false
}
} else if !ok1 && !ok2 {
// both of channel are empty!
return true
}
}
return false
}
func main() {
a := tree.New(2)
walker := make(chan int)
go Walk(a, walker)
for v := range walker {
fmt.Print(v,"|")
}
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(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