tree.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Go's concurrency primitives make it easy to
  2. // express concurrent concepts, such as
  3. // this binary tree comparison.
  4. //
  5. // Trees may be of different shapes,
  6. // but have the same contents. For example:
  7. //
  8. // 4 6
  9. // 2 6 4 7
  10. // 1 3 5 7 2 5
  11. // 1 3
  12. //
  13. // This program compares a pair of trees by
  14. // walking each in its own goroutine,
  15. // sending their contents through a channel
  16. // to a third goroutine that compares them.
  17. package main
  18. import (
  19. "fmt"
  20. "math/rand"
  21. )
  22. // A Tree is a binary tree with integer values.
  23. type Tree struct {
  24. Left *Tree
  25. Value int
  26. Right *Tree
  27. }
  28. // Walk traverses a tree depth-first,
  29. // sending each Value on a channel.
  30. func Walk(t *Tree, ch chan int) {
  31. if t == nil {
  32. return
  33. }
  34. Walk(t.Left, ch)
  35. ch <- t.Value
  36. Walk(t.Right, ch)
  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. // Compare reads values from two Walkers
  49. // that run simultaneously, and returns true
  50. // if t1 and t2 have the same contents.
  51. func Compare(t1, t2 *Tree) bool {
  52. c1, c2 := Walker(t1), Walker(t2)
  53. for {
  54. v1, ok1 := <-c1
  55. v2, ok2 := <-c2
  56. if !ok1 || !ok2 {
  57. return ok1 == ok2
  58. }
  59. if v1 != v2 {
  60. break
  61. }
  62. }
  63. return false
  64. }
  65. // New returns a new, random binary tree
  66. // holding the values 1k, 2k, ..., nk.
  67. func New(n, k int) *Tree {
  68. var t *Tree
  69. for _, v := range rand.Perm(n) {
  70. t = insert(t, (1+v)*k)
  71. }
  72. return t
  73. }
  74. func insert(t *Tree, v int) *Tree {
  75. if t == nil {
  76. return &Tree{nil, v, nil}
  77. }
  78. if v < t.Value {
  79. t.Left = insert(t.Left, v)
  80. return t
  81. }
  82. t.Right = insert(t.Right, v)
  83. return t
  84. }
  85. func main() {
  86. t1 := New(100, 1)
  87. fmt.Println(Compare(t1, New(100, 1)), "Same Contents")
  88. fmt.Println(Compare(t1, New(99, 1)), "Differing Sizes")
  89. fmt.Println(Compare(t1, New(100, 2)), "Differing Values")
  90. fmt.Println(Compare(t1, New(101, 2)), "Dissimilar")
  91. }