这一章做个练习,运用协程和管道对二叉树进行先序遍历
上代码:
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) {
stack := []*tree.Tree{} // 定义一个栈,栈存的就是一棵树
root := t
for root != nil || len(stack) > 0 {
for root != nil {
stack = append(stack, root) // 1.先将整颗树怼进去,在把所有的左子树怼进去
root = root.Left // 2.遍历左子树,直接左边的最下边
}
root = stack[len(stack)-1] // 3.因为先进后出,拿到了最下面的左节点
stack = stack[:len(stack)-1] // 对栈列表进行切片,相当于弹出操作
ch <- root.Value // 塞到管道里
root = root.Right //5.看以右节点为根的还有没有左节点,有就回到上面第1步,没有就走第3步,把根节点
}
close(ch)
}
// 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)
for i := range ch1 {
j := <-ch2
if i != j { // 对比数据
return false
}
}
return true
}
func main() {
ch := make(chan int, 10)
go Walk(tree.New(1), ch)
for i := range ch {
fmt.Println(i)
}
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
哦了,很好的一道结合数据结构和协程知识点的练习。
主要难点就是二叉树先序遍历的实现,直接谷歌搞定,哈哈。
复制粘贴的代码一定要读一遍,理解他的逻辑。
日积月累,每个人都能成为大神的。