Skip to content

Instantly share code, notes, and snippets.

@Version2beta
Created August 30, 2021 02:46
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 Version2beta/e0cb15119c493b8aac8cc518401c7a47 to your computer and use it in GitHub Desktop.
Save Version2beta/e0cb15119c493b8aac8cc518401c7a47 to your computer and use it in GitHub Desktop.
A Tour of Go Exercise: Equivalent Binary Trees
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
func Walk(t *tree.Tree, ch chan int) {
if t == nil {
return
}
Walk(t.Left, ch)
ch <- t.Value
Walk(t.Right, ch)
return
}
func Same(t1, t2 *tree.Tree) bool {
// var r1, r2 []int
c1, c2 := make(chan int, 10), make(chan int, 10)
go Walk(t1, c1)
go Walk(t2, c2)
for i := 0; i < 10; i++ {
v1 := <-c1
v2 := <-c2
if v1 != v2 {
return false
}
}
return true
}
func main() {
t1 := tree.New(1)
t2 := tree.New(1)
t3 := tree.New(3)
ch := make(chan int)
go Walk(t1, ch)
for i := 0; i < 10; i++ {
fmt.Printf("%v ", <-ch)
}
fmt.Print("\nt1 and t2 same? ", Same(t1, t2))
fmt.Print("\nt1 and t3 same? ", Same(t1, t3))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment