Go語言實現的樹形結構數據比較算法實例
本文實例講述了Go語言實現的樹形結構數據比較算法。分享給大家供大家參考。具體實現方法如下:
// Two binary trees may be 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 Tree 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, 100)), "Same Contents")
fmt.Println(Compare(t1, New(1, 99)), "Differing Sizes")
fmt.Println(Compare(t1, New(2, 100)), "Differing Values")
fmt.Println(Compare(t1, New(2, 101)), "Dissimilar")
}
希望本文所述對大家的Go語言程序設計有所幫助。
相關文章
Golang 實現 Redis系列(六)如何實現 pipeline 模式的 redis 客戶端
pipeline 模式的 redis 客戶端需要有兩個后臺協程負責 tcp 通信,調用方通過 channel 向后臺協程發(fā)送指令,并阻塞等待直到收到響應,本文是使用 golang 實現 redis 系列的第六篇, 將介紹如何實現一個 Pipeline 模式的 Redis 客戶端。2021-07-07
Go語言異常處理(Panic和recovering)用法詳解
異常處理是程序健壯性的關鍵,往往開發(fā)人員的開發(fā)經驗的多少從異常部分處理上就能得到體現。Go語言中沒有Try?Catch?Exception機制,但是提供了panic-and-recover機制,本文就來詳細講講他們的用法2022-07-07

