56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
package main
|
|
|
|
import "golang.org/x/tour/tree"
|
|
|
|
import (
|
|
"fmt"
|
|
"sort"
|
|
)
|
|
|
|
// 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.Value > 0 {
|
|
ch <- t.Value
|
|
}
|
|
if t.Left != nil {
|
|
go Walk(t.Left, ch)
|
|
}
|
|
if t.Right != nil {
|
|
go Walk(t.Right, ch)
|
|
}
|
|
}
|
|
|
|
// Same determines whether the trees
|
|
// t1 and t2 contain the same values.
|
|
func Same(t1, t2 *tree.Tree) bool {
|
|
s1 := make([]int, 10)
|
|
s2 := make([]int, 10)
|
|
ch1 := make(chan int)
|
|
ch2 := make(chan int)
|
|
go Walk(t1, ch1)
|
|
go Walk(t2, ch2)
|
|
for i := 0; i < 10; i++ {
|
|
s1 = append(s1, <- ch1)
|
|
s2 = append(s2, <- ch2)
|
|
}
|
|
sort.Ints(s1)
|
|
sort.Ints(s2)
|
|
for i, _ := range s1 {
|
|
if s1[i] != s2[i] {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func main() {
|
|
ch := make(chan int)
|
|
go Walk(tree.New(1), ch)
|
|
for i := 0; i < 10; i++ {
|
|
fmt.Println(<- ch)
|
|
}
|
|
fmt.Println(Same(tree.New(1), tree.New(1)))
|
|
fmt.Println(Same(tree.New(1), tree.New(2)))
|
|
}
|