A Tour of Go の Exercise を実施したときのメモ。
Walk の処理
treeをたどりながら channel に値を書き出す。
- まず、Left を端までたどる(Leftで Walk を再帰呼び出し)
- 末端(t == nil)になったら tree を戻る
- 戻ったところで Valueを出力し、Right で Walk を再帰呼び出し
exercise-equivalent-binary-trees.go
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 == nil {
return
}
Walk(t.Left, ch)
ch <- t.Value
//fmt.Println("V: ", 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 {
return true
}
func main() {
ch := make(chan int, 10)
go Walk(tree.New(1), ch)
// for c := range ch {
// fmt.Println(c)
// }
for i := 0; i < cap(ch); i++ {
fmt.Println(<-ch)
}
}
Walk の処理2
-
t.Left == nil && t.Right == nil
の条件を追加すると、再帰呼び出しの回数が減らせる - ただ、判定処理が追加になるので速度がどうなるか
func Walk(t *tree.Tree, ch chan int) {
switch {
case t == nil:
case t.Left == nil && t.Right == nil:
ch <- t.Value
fmt.Println("N: ", t.Value)
default:
Walk(t.Left, ch)
ch <- t.Value
fmt.Println("V: ", t.Value)
Walk(t.Right, ch)
}
}
Same の処理
- 2つのtreeをそれぞれWalkで処理し、channel の値を順に読み出して比較する
- どれか1つでも異なるものがあれば false にする
- が、内容確認のため全件確認している
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int, 10)
ch2 := make(chan int, 10)
go Walk(t1, ch1)
go Walk(t2, ch2)
ret := true
for i := 0; i < cap(ch1); i++ {
i1 := <-ch1
i2 := <-ch2
fmt.Println(i1, i2)
if i1 != i2 {
ret = false
}
}
return ret
}