Skip to content

Instantly share code, notes, and snippets.

@moccos
Created April 13, 2019 06:24
Show Gist options
  • Save moccos/8893e117b8db069cf87fb41689b185de to your computer and use it in GitHub Desktop.
Save moccos/8893e117b8db069cf87fb41689b185de to your computer and use it in GitHub Desktop.
A Tour of Go Exercise: Equivalent Binary Trees https://tour.golang.org/concurrency/8
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
// 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 {
return
}
WalkImpl(t, ch)
close(ch)
}
func WalkImpl(t *tree.Tree, ch chan int) {
if t.Left != nil {
WalkImpl(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
WalkImpl(t.Right, ch)
}
}
// 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)
go Walk(t1, ch1)
go Walk(t2, ch2)
var a1, a2 []int
for n := range ch1 {
a1 = append(a1, n)
}
for n := range ch2 {
a2 = append(a2, n)
}
if len(a1) != len(a2) {
return false
}
for i := range a1 {
if a1[i] != a2[i] {
return false
}
}
return true
}
func checkWalk(n int) {
ch := make(chan int)
t := tree.New(n)
fmt.Printf("%v\n", t)
go Walk(t, ch)
for n := range ch {
fmt.Printf("%d\n", n)
}
}
func checkSame(n int) {
t1, t2 := tree.New(n), tree.New(n)
fmt.Printf("%v\n", t1)
fmt.Printf("%v\n", t2)
fmt.Print(Same(t1, t2))
}
func main() {
// checkWalk(1)
checkSame(2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment