go语言Exercise: Equivalent Binary Trees
2012-05-09 17:48
423 查看
1. Implement the
2. Test the
The function
...,
Create a new channel
Then read and print 10 values from the channel. It should be the numbers 1, 2, 3, ..., 10.
3. Implement the
determine whether
4. Test the
package main
import (
"tour/tree"
"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.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
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)
ch2 := make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := 0; i < 10; i++ {
if <-ch1 != <-ch2 {
return false
}
}
return true
}
func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
for i := 0; i < 10; i++ {
fmt.Println(<-ch)
}
fmt.Println("Equivalent Binary Trees?",Same(tree.New(1), tree.New(1)))
fmt.Println("Equivalent Binary Trees?",Same(tree.New(1), tree.New(2)))
}
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.
package main
import (
"tour/tree"
"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.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
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)
ch2 := make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := 0; i < 10; i++ {
if <-ch1 != <-ch2 {
return false
}
}
return true
}
func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
for i := 0; i < 10; i++ {
fmt.Println(<-ch)
}
fmt.Println("Equivalent Binary Trees?",Same(tree.New(1), tree.New(1)))
fmt.Println("Equivalent Binary Trees?",Same(tree.New(1), tree.New(2)))
}
相关文章推荐
- A Tour of Go - Exercise: Equivalent Binary Trees
- 【GoLang笔记】A Tour of Go - Exercise: Equivalent Binary Trees
- Go Exercise: Equivalent Binary Trees
- go语言Exercise: Errors
- go语言Exercise: Images
- Go 语言实现exercise--Loops and Functions
- go语言Exercise: Rot13 Reader
- Go指南练习之《等价二叉树》(Equivalent Binary Trees)
- go语言Exercise: Maps
- go语言Exercise: Slices
- go语言Exercise: Fibonacci closure
- go语言Advanced Exercise: Complex cube roots
- 数据结构:Binary and other trees(数据结构,算法及应用(C++叙事描述语言)文章8章)
- go语言和资料
- go语言之json的使用
- go语言中操作mysql的方法
- 95. Unique Binary Search Trees II
- Unique Binary Search Trees II
- Go语言与面向对象编程
- Go语言基础学习教程