Skip to content

Instantly share code, notes, and snippets.

@krry
Created March 4, 2019 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krry/07d79056a26514ad64cdf1872b634fc7 to your computer and use it in GitHub Desktop.
Save krry/07d79056a26514ad64cdf1872b634fc7 to your computer and use it in GitHub Desktop.
An Answer to A Tour of Go Exercise: Equivalent Binary Trees
package main
import (
"golang.org/x/tour/tree"
"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 { // if empty node, stop looking
Walk(t.Left, ch) // otherwise, look left first
ch <- t.Value // send the current node to the channel
Walk(t.Right, ch) // and look right
} // continue until all looks come up empty
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1, ch2 := make(chan int), make(chan int) // make channels
go func() { // go to the first tree
Walk(t1, ch1) // kick off the walker
close(ch1) // wait to close until the walk is done
}() // call the go
go func() { // repeat for the second tree
Walk(t2, ch2)
close(ch2)
}()
for i := range ch1 { // iterate over one of the channels
if i != <-ch2 { // at each step, see if nodes are the same
return false // if not, trees are not the same
}
}
return true // if no dissimilar nodes, trees are the same
}
func main() {
ch := make(chan int)
go func() { // test walk a tree
Walk(tree.New(1), ch)
close(ch) // make sure to close when walk is done
}()
for i := range ch {
fmt.Println(i)
}
fmt.Println(Same(tree.New(1), tree.New(1))) // should be true
fmt.Println(Same(tree.New(1), tree.New(2))) // should be false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment