木の比較のためのゴーツアー演習 (#69) を完了し、2 本の木を効果的に比較することができました。
ここにコードがあります
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
// 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)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
c := make(chan int)
c2 := make(chan int)
go Walk(t1, c)
go Walk(t2, c2)
for i := 0; i < 10; i++ {
if <-c != <-c2 {
return false
}
}
return true
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(1)))
}
私を混乱させる部分は、ウォーク関数のコマンドの順序を入れ替えると
ch <- t.Value
Walk(t.Right,ch)
Walk(t.Left,ch)
比較は機能しなくなります。Walk(tree.New(1),c) の結果を 2 回印刷しようとしましたが、奇妙なことに最初の呼び出しが印刷されました
10,5,7,9...
Walk(tree.New(1),c) の 2 回目の呼び出しが出力されている間
7,9,10,8...
walk コマンドの順序を切り替えるときに、同じ関数を 2 回呼び出すと、2 つの異なる出力が生じるのはなぜですか?