Skip to content

Instantly share code, notes, and snippets.

@fr-xiaoli
Created November 17, 2018 04:25
Show Gist options
  • Select an option

  • Save fr-xiaoli/0425b1411cf3d6dc1fc551298003b93c to your computer and use it in GitHub Desktop.

Select an option

Save fr-xiaoli/0425b1411cf3d6dc1fc551298003b93c to your computer and use it in GitHub Desktop.
A Tour of Go - Concurrency - Exercise: Equivalent Binary Trees
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) {
walk(t, ch)
close(ch)
}
func walk(t *tree.Tree, ch chan int) {
if t.Left != nil {
walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
walk(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 v := range ch1 {
if v != <-ch2 { return false }
}
return true
}
func main() {
fmt.Print("Test Walk: ")
ch := make(chan int, 10)
go Walk(tree.New(1), ch)
fmt.Print(<-ch)
for i := range ch {
fmt.Printf(", %d", i)
}
fmt.Print("\n")
fmt.Println("Test Same (1): Same(tree.New(1), tree.New(1)) should return true: ", Same(tree.New(1), tree.New(1)))
fmt.Println("Test Same (2): Same(tree.New(1), tree.New(2)) should return 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