Skip to content

Instantly share code, notes, and snippets.

@EJSohn
Created April 22, 2019 15:43
Show Gist options
  • Select an option

  • Save EJSohn/9400aacd6e1c2a700d89c82b3e58b4f7 to your computer and use it in GitHub Desktop.

Select an option

Save EJSohn/9400aacd6e1c2a700d89c82b3e58b4f7 to your computer and use it in GitHub Desktop.
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
recursiveWalk(t, ch)
close(ch) // close channel when done
}
func recursiveWalk(t *tree.Tree, ch chan int) {
if t != nil {
// in order
recursiveWalk(t.Left, ch)
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 {
// create channels to message pass
ch1 := make(chan int)
ch2 := make(chan int)
// create goroutines with channels
go Walk(t1, ch1)
go Walk(t2, ch2)
for {
// receive message from channels concurrently
v1, ok1 := <-ch1
v2, ok2 := <-ch2
// something in the tree isn't the same
if v1 != v2 || ok1 != ok2 {
return false
}
// got to end with everything equal
if !ok1 {
break
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment