[Go] Go语言实现的树形结构数据比较算法的代码片段 →→→→→进入此内容的聊天室

来自 , 2019-11-07, 写在 Go, 查看 138 次.
URL http://www.code666.cn/view/6c35083f
  1. // Two binary trees may be of different shapes,
  2. // but have the same contents. For example:
  3. //
  4. //        4               6
  5. //      2   6          4     7
  6. //     1 3 5 7       2   5
  7. //                  1 3
  8. //
  9. // Go's concurrency primitives make it easy to
  10. // traverse and compare the contents of two trees
  11. // in parallel.
  12.  
  13. package main
  14.  
  15. import (
  16.         "fmt"
  17.         "rand"
  18. )
  19.  
  20. // A Tree is a binary tree with integer values.
  21. type Tree struct {
  22.         Left  *Tree
  23.         Value int
  24.         Right *Tree
  25. }
  26.  
  27. // Walk traverses a tree depth-first,
  28. // sending each Value on a channel.
  29. func Walk(t *Tree, ch chan int) {
  30.         if t == nil {
  31.                 return
  32.         }
  33.         Walk(t.Left, ch)
  34.         ch <- t.Value
  35.         Walk(t.Right, ch)
  36. }
  37.  
  38. // Walker launches Walk in a new goroutine,
  39. // and returns a read-only channel of values.
  40. func Walker(t *Tree) <-chan int {
  41.         ch := make(chan int)
  42.         go func() {
  43.                 Walk(t, ch)
  44.                 close(ch)
  45.         }()
  46.         return ch
  47. }
  48.  
  49. // Compare reads values from two Walkers
  50. // that run simultaneously, and returns true
  51. // if t1 and t2 have the same contents.
  52. func Compare(t1, t2 *Tree) bool {
  53.         c1, c2 := Walker(t1), Walker(t2)
  54.         for <-c1 == <-c2 {
  55.                 if closed(c1) || closed(c1) {
  56.                         return closed(c1) == closed(c2)
  57.                 }
  58.         }
  59.         return false
  60. }
  61.  
  62. // New returns a new, random binary tree
  63. // holding the values 1k, 2k, ..., nk.
  64. func New(n, k int) *Tree {
  65.         var t *Tree
  66.         for _, v := range rand.Perm(n) {
  67.                 t = insert(t, (1+v)*k)
  68.         }
  69.         return t
  70. }
  71.  
  72. func insert(t *Tree, v int) *Tree {
  73.         if t == nil {
  74.                 return &Tree{nil, v, nil}
  75.         }
  76.         if v < t.Value {
  77.                 t.Left = insert(t.Left, v)
  78.                 return t
  79.         }
  80.         t.Right = insert(t.Right, v)
  81.         return t
  82. }
  83.  
  84. func main() {
  85.         t1 := New(1, 100)
  86.         fmt.Println(Compare(t1, New(1, 100)), "Same Contents")
  87.         fmt.Println(Compare(t1, New(1, 99)), "Differing Sizes")
  88.         fmt.Println(Compare(t1, New(2, 100)), "Differing Values")
  89.         fmt.Println(Compare(t1, New(2, 101)), "Dissimilar")
  90. }
  91.  
  92. //go/4354

回复 "Go语言实现的树形结构数据比较算法的代码片段"

这儿你可以回复上面这条便签

captcha