0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【A Tour of Go】Concurrency/Exercise: Equivalent Binary Trees (8/11)

Posted at

A Tour of Go の Exercise を実施したときのメモ。

Walk の処理

treeをたどりながら channel に値を書き出す。

  1. まず、Left を端までたどる(Leftで Walk を再帰呼び出し)
  2. 末端(t == nil)になったら tree を戻る
  3. 戻ったところで 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
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?