This is a creation in Article, where the information may have evolved or changed.
A Tour of Go
Exercise:equivalent Binary Trees
There can many different binary trees with the same sequence of values stored at the leaves. For example, here is the binary trees storing the sequence 1, 1, 2, 3, 5, 8, 13.
A function to check whether binary trees store the same sequence are quite complex in most languages. We'll use the Go ' s concurrency and channels to write a simple solution.
This example uses tree
the package, which defines the type:
Type Tree struct {left *treevalue intright *tree}
1. Implement the Walk
function.
2. Test the Walk
function.
The function tree.New(k)
constructs a randomly-structured binary tree holding the values k
,,, 2k
3k
... 10k
.
Create a new channel and ch
kick off the walker:
Go Walk (tree. New (1), CH)
Then read and print ten values from the channel. It should be the numbers 1, 2, 3, ..., 10.
3. Implement the Same
function using to Walk
determine whether and t1
store the t2
same values.
4. Test the Same
function.
Same(tree.New(1), tree.New(1))
Should return true, and Same(tree.New(1), tree.New(2))
should return false.
Package Mainimport "Tour/tree" import "FMT"//Walk walks the tree t sending all values//from the tree to the channel Ch.fu NC 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 dete Rmines 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) Result: = truefor I: = 0; i < 10; i + + {v1: = <-ch1v2: = <-Ch2result = (V1 = = v2)}return Result}func Main () {//ch: = make (chan int)//go Walk (TREE.N EW (1), ch)//for I: = 0; I < 10; i + + {//v: = <-ch//fmt. Println (v)//}fmt. Println (same, tree. New (1), tree. New (1))) FMT. Println (same, tree. New (1), tree. New (2))}