Go語言實現的樹形結構資料比較演算法執行個體_Golang

來源:互聯網
上載者:User

本文執行個體講述了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語言程式設計有所協助。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.