Skip to content

Instantly share code, notes, and snippets.

@haisum
Created August 28, 2017 20:51
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 haisum/1e733a60e326f40789b12128539aa869 to your computer and use it in GitHub Desktop.
Save haisum/1e733a60e326f40789b12128539aa869 to your computer and use it in GitHub Desktop.
equivalent binary trees
package main
import (
"golang.org/x/tour/tree"
"fmt"
"time"
)
// 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
}
Walk(t.Left, ch)
ch <- t.Value
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, 10)
ch2 := make(chan int, 10)
count := 1
go Walk(t1, ch1)
go Walk(t2, ch2)
for x := range ch1 {
y := <-ch2
fmt.Printf("%d %d \n", x, y)
if x != y {
return false
}
if count == 10 {
break
}
count++
}
return true
}
func main() {
start := time.Now()
fmt.Printf("%v\n", Same(tree.New(1), tree.New(1)))
fmt.Printf("%v\n", Same(tree.New(2), tree.New(2)))
fmt.Printf("%s", time.Since(start))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment