Go language exercise:equivalent Binary Trees

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

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 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)))
}

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.