Skip to content

Instantly share code, notes, and snippets.

@danimal141
Last active October 11, 2016 13:26
Show Gist options
  • Save danimal141/2641d1596bc959831bd068765cfb2e0f to your computer and use it in GitHub Desktop.
Save danimal141/2641d1596bc959831bd068765cfb2e0f to your computer and use it in GitHub Desktop.
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) {
var walker func(t *tree.Tree)
walker = func(t *tree.Tree) {
if t.Left != nil {
walker(t.Left)
}
ch <- t.Value
if t.Right != nil {
walker(t.Right)
}
}
walker(t)
close(ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for {
n1, ok1 := <- ch1
n2, ok2 := <- ch2
if n1 != n2 || ok1 != ok2 {
return false
}
if !ok1 {
break
}
}
return true
}
func main() {
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