[Go语言]我的第十个Go语言程序
2016-08-02 20:45
369 查看
Exercise: Equivalent Binary Trees
There can be many different binary trees with the same sequence of values stored at the leaves. For example, here are two binary trees storing the sequence 1, 1, 2, 3, 5, 8, 13.A function to check whether two binary trees store the same sequence is quite complex in most languages. We'll use Go's concurrency and channels to write a simple solution.
This example uses the
treepackage, which defines the type:
type Tree struct { Left *Tree Value int Right *Tree }
Continue description on next page.
1. Implement the
Walkfunction.
2. Test the
Walkfunction.
The function
tree.New(k)constructs a randomly-structured binary tree holding the values
k,
2k,
3k,
...,
10k.
Create a new channel
chand kick off the walker:
go Walk(tree.New(1), ch)
Then read and print 10 values from the channel. It should be the numbers 1, 2, 3, ..., 10.
3. Implement the
Samefunction using
Walkto
determine whether
t1and
t2store
the same values.
4. Test the
Samefunction.
Same(tree.New(1), tree.New(1))should return true, and
Same(tree.New(1), tree.New(2))should return false.
The documentation for
Treecan be found here.
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) {
if t == nil {
return
}
Walk(t.Left, ch)
ch <- 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 {
ch1 := make(chan int, 10)
ch2 := make(chan int, 10)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := 0; i <10; i++ {
a := <- ch1
b := <- ch2
if a != b {
return false
}
}
return true
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
相关文章推荐
- Go语言日趋成熟 运行速度接近C语言实现程序
- go语言 -并行程序 wordcount
- 创建第一个Go语言程序Hello,Go!
- go语言实现的目录共享程序
- 关于GDB调试go语言程序中出现 os.Args无法打印的问题
- Go语言学习札记——第三章 Go基本的程序设计结构(1)
- 在Go语言程序中使用gojson来解析JSON格式文件
- Go语言程序的状态监控 via 达达
- go语言编写,简单聊天室程序 1
- 使用GO语言开发 Redis数据监控程序
- Goclipse中运行Go语言程序的配置
- go语言编写Web程序
- 我的第一个比较实用的GO语言程序
- Go语言程序的状态监控
- Go 语言中实现优雅的停止程序
- 在go语言中统计程序执行时间
- Eclipse里编写Go语言程序
- Sublim Text 开发Go语言程序
- Windows下使用go语言写程序安装配置实例
- Go语言监控文件变化小程序.