Skip to content

Instantly share code, notes, and snippets.

@jdenly
Last active January 12, 2022 04:50
Show Gist options
  • Save jdenly/259bdde37ff61c22113577b3d8ebd3df to your computer and use it in GitHub Desktop.
Save jdenly/259bdde37ff61c22113577b3d8ebd3df to your computer and use it in GitHub Desktop.
Solution to A Tour of Go - Exercise: Equivalent Binary Trees
package main
import "golang.org/x/tour/tree"
import "fmt"
import "reflect"
// 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)
// Need this inner recursion to allow me to close the channel.
walk = func(t *tree.Tree) {
if t == nil {
return
}
walk(t.Left)
ch <- t.Value
walk(t.Right)
}
walk(t)
close(ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch, ch2 := make(chan int), make(chan int)
go Walk(t1, ch)
go Walk(t2, ch2)
t1s, t2s := make([]int, 0), make([]int, 0)
for i := range ch {
t1s = append(t1s, i)
}
for i := range ch2 {
t2s = append(t2s, i)
}
// Not the fastest way of comparing, very convenient though :)
return reflect.DeepEqual(t1s, t2s)
}
func main() {
fmt.Println("Should be true:", Same(tree.New(1), tree.New(1)))
fmt.Println("Should be false:", 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