Skip to content

Instantly share code, notes, and snippets.

@guoxingx
Created May 18, 2018 17:16
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 guoxingx/e97d9e196af2e109d7eef8c3647aa777 to your computer and use it in GitHub Desktop.
Save guoxingx/e97d9e196af2e109d7eef8c3647aa777 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) {
WalkLoop(t, ch)
close(ch)
}
func WalkLoop(t *tree.Tree, ch chan int) {
if t != nil {
WalkLoop(t.Left, ch)
ch <- t.Value
WalkLoop(t.Right, 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 i := range ch1 {
if i != <- ch2 { return false }
}
return true
}
func main() {
ch := make(chan int)
t1 := tree.New(1)
t2 := tree.New(2)
go Walk(t1, ch)
fmt.Println(Same(t1, t2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment