【发布时间】:2021-09-17 22:00:06
【问题描述】:
func New(k int) *Tree
// New() returns a random binary tree holding the values k, 2k, ..., 10k.
我只是在 goroutine 中尝试遍历二叉树并向通道添加值。然后在 main goroutine 中打印它们
代码
func binary(t *tree.Tree, ch chan int) {
if t != nil {
binary(t.Left, ch)
ch <- t.Value
binary(t.Right, ch)
}
}
func Walk(t *tree.Tree, ch chan int) {
defer close(ch)
binary(t, ch)
}
func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
for i := range ch {
fmt.Printf("%d ", <-ch)
_ = i
}
}
预期输出 = 1 2 3 4 5 6 7 8 9 10
结果 = 2 4 6 8 10
【问题讨论】:
标签: go concurrency channel