Skip to content

Instantly share code, notes, and snippets.

@talonx
Created December 14, 2015 18:39
Show Gist options
  • Save talonx/21caa0bf7caa527f84b5 to your computer and use it in GitHub Desktop.
Save talonx/21caa0bf7caa527f84b5 to your computer and use it in GitHub Desktop.
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)
}
func WalkAndClose(t *tree.Tree, ch chan int) {
Walk(t, ch)
close(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 WalkAndClose(t1, ch1)
go WalkAndClose(t2, ch2)
for {
v1, ok1 := <- ch1
v2, ok2 := <- ch2
if ok1 != ok2 {
return false
}
if !ok1 && !ok2 {
return true
}
if v1 != v2 {
return false
}
}
return true
}
func testWalk(t *tree.Tree) {
ch := make(chan int)
go Walk(t, ch)
for v := range ch {
fmt.Println(v)
}
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(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