Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Created August 30, 2015 23:17
Show Gist options
  • Select an option

  • Save colelawrence/53e0d092677d39d4f781 to your computer and use it in GitHub Desktop.

Select an option

Save colelawrence/53e0d092677d39d4f781 to your computer and use it in GitHub Desktop.
package main
import "golang.org/x/tour/tree"
import "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.Left != nil { _walk(t.Left, ch) }
ch <- t.Value
if t.Right != nil { _walk(t.Right, ch) }
}
func Walk(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, ch2 := make(chan int), make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for val := range ch1 {
if val != <- ch2 {
return false
}
}
return true
}
func main() {
t1 := tree.New(1)
t2 := tree.New(1)
fmt.Println(Same(t1, t2))
fmt.Println(Same(t1, tree.New(2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment