2012-09-03 20:15:50 -07:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"code.google.com/p/go-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) {
|
2012-09-03 20:18:02 -07:00
|
|
|
// do it as a nested closure so that I can control the call to close so
|
|
|
|
// that I can use the range-based forloop in main.main
|
|
|
|
var walk func(t *tree.Tree)
|
|
|
|
walk = func(t *tree.Tree) {
|
2012-09-03 20:27:24 -07:00
|
|
|
if t != nil {
|
2012-09-03 20:18:02 -07:00
|
|
|
walk(t.Left)
|
|
|
|
ch <- t.Value
|
|
|
|
walk(t.Right)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
walk(t)
|
2012-09-03 20:15:50 -07:00
|
|
|
close(ch)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Same determines whether the trees
|
|
|
|
// t1 and t2 contain the same values.
|
2012-09-03 20:27:24 -07:00
|
|
|
func Same(t1, t2 *tree.Tree) bool {
|
|
|
|
ch1 := make(chan int)
|
|
|
|
ch2 := make(chan int)
|
|
|
|
go Walk(t1, ch1)
|
|
|
|
go Walk(t2, ch2)
|
|
|
|
for i := range ch1 {
|
|
|
|
if i != <-ch2 {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
2012-09-03 20:15:50 -07:00
|
|
|
|
|
|
|
func main() {
|
|
|
|
t := tree.New(1)
|
|
|
|
ch := make(chan int)
|
|
|
|
go Walk(t, ch)
|
|
|
|
for i := range ch {
|
|
|
|
fmt.Printf("%d, ", i)
|
|
|
|
}
|
|
|
|
fmt.Println()
|
2012-09-03 20:27:24 -07:00
|
|
|
fmt.Println(Same(tree.New(1), tree.New(1)))
|
|
|
|
fmt.Println(Same(tree.New(1), tree.New(2)))
|
2012-09-03 20:15:50 -07:00
|
|
|
}
|