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:
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.