A Tour of Go-exercise:equivalent Binary Trees

Source: Internet
Author: User
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))}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.