A case study of the tree structure data comparison algorithm implemented by Go language _golang

Source: Internet
Author: User

This paper illustrates the tree-structured data comparison algorithm of Go language implementation. Share to everyone for your reference. The implementation methods are as follows:

Copy Code code as follows:

Two binary trees may is of different shapes,
But have the same contents. For example:
//
4 6
2 6 4 7
1 3 5 7 2 5
1 3
//
Go ' s concurrency primitives make it easy to
Traverse and compare the contents of two trees
In parallel.

Package Main
Import (
"FMT"
"Rand"
)

A is a binary tree with integer values.
Type tree struct {
Left *tree
Value int
Right *tree
}

Walk traverses a tree Depth-first,
Sending each Value on a channel.
Func Walk (t *tree, ch Chan int) {
If T = = Nil {
Return
}
Walk (T.left, ch)
CH <-t.value
Walk (t.right, ch)
}

Walker launches Walk in a new goroutine,
and returns a read-only channel of values.
Func Walker (t *tree) <-chan int {
CH: = make (chan int)
Go func () {
Walk (t, ch)
Close (CH)
}()
return CH
}

Compare reads values from two walkers
That run simultaneously, and returns True
If T1 and T2 have the same contents.
Func Compare (t1, T2 *tree) bool {
C1, C2: = Walker (T1), Walker (T2)
for <-c1 = = <-C2 {
If closed (C1) | | Closed (C1) {
Return closed (C1) = = Closed (C2)
}
}
return False
}

New returns a new, Random binary tree
Holding the values 1k, 2k, ..., NK.
Func New (n, K int) *tree {
var t *tree
For _, V: = range rand. Perm (n) {
t = Insert (t, (1+V) *k)
}
Return T
}

Func Insert (t *tree, v int) *tree {
If T = = Nil {
Return &tree{nil, V, nil}
}
If v < t.value {
T.left = insert (T.left, V)
Return T
}
T.right = insert (T.right, V)
Return T
}

Func Main () {
T1: = New (1, 100)
Fmt. Println (Compare (T1, New (1)), "Same Contents")
Fmt. Println (Compare (T1, New (1)), "differing sizes")
Fmt. Println (Compare (T1, New (2)), "differing Values")
Fmt. Println (Compare (T1, New (2)), "dissimilar")
}

I hope this article will help you with your go language program.

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.