Skip to content

Instantly share code, notes, and snippets.

@ksomemo
Last active August 29, 2015 14:04
Show Gist options
  • Save ksomemo/caa36311bf3507518332 to your computer and use it in GitHub Desktop.
Save ksomemo/caa36311bf3507518332 to your computer and use it in GitHub Desktop.
package main
import "code.google.com/p/go-tour/tree"
import (
"fmt"
)
/*
type Tree struct {
Left *Tree
Value int
Right *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 := func(t *tree.Tree) {}
walk = func(t *tree.Tree) {
if t != nil {
walk(t.Left)
ch <- t.Value
walk(t.Right)
}
}
walk(t)
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 Walk(t1, ch1)
go Walk(t2, ch2)
/*
for v1 := range ch1 {
if v1 != <-ch2 {
return false
}
}
*/
for {
v1, ok1 := <-ch1
v2, ok2 := <-ch2
if v1 != v2 {
return false
}
if !ok1 && !ok2 {
break
}
}
return true
}
func main() {
ch := make(chan int)
t := tree.New(1)
go Walk(t, ch)
for v := range ch {
fmt.Print(v, " ")
}
fmt.Println("")
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