Skip to content

练习

二叉树

https://go.dev/tour/concurrency/8

go
package main


import (
	"fmt"
	"golang.org/x/tour/tree"
)

// Walk 会沿着树结构遍历,将树中的所有值发送至通道 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用于判断树t1和t2是否包含相同的值。
// func Same(t1, t2 *tree.Tree) bool

func main() {
	ch := make(chan int)
	go func(){
		Walk(tree.New(1), ch)
		close(ch)
	}()
	for i:=0;i<10;i++{
		fmt.Print(<-ch," ")
	}
	for range ch {
	}
}