Skip to content

Instantly share code, notes, and snippets.

@SergeyNarozhny
Created March 25, 2017 18:47
Show Gist options
  • Save SergeyNarozhny/0138c501b38c4fc8a161aace20bcba57 to your computer and use it in GitHub Desktop.
Save SergeyNarozhny/0138c501b38c4fc8a161aace20bcba57 to your computer and use it in GitHub Desktop.
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) {
if t == nil {
return
}
Walk(t.Left, ch)
ch <- t.Value
Walk(t.Right, ch)
}
// Returns channel for reading only
func Walker(t *tree.Tree, printed bool) <-chan int {
ch := make(chan int)
go func() {
Walk(t, ch)
close(ch)
}()
if (printed) {
for i := range ch {
fmt.Println(i)
}
}
return ch
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
c1, c2 := Walker(t1, false), Walker(t2, false)
for {
v1, ok1 := <-c1
v2, ok2 := <-c2
if !ok1 || !ok2 {
return ok1 == ok2
}
if v1 != v2 {
break
}
}
return false
}
func main() {
t := tree.New(1)
fmt.Printf("%T %v\n", t, t)
Walker(t, true)
test1, test2 := Same(tree.New(1), tree.New(1)), Same(tree.New(1), tree.New(2))
fmt.Println(test1, test2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment