Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.74 KB | None | 0 0
  1. import (
  2. "fmt"
  3. "golang.org/x/tour/tree"
  4. )
  5.  
  6. // Walk walks the tree t sending all values
  7. // from the tree to the channel ch.
  8. func Walk(t *tree.Tree, ch chan int) {
  9. if t.Left != nil {
  10. go Walk(t.Left, ch)
  11. }
  12.  
  13. ch <- t.Value
  14.  
  15. if t.Right != nil {
  16. go Walk(t.Right, ch)
  17. }
  18.  
  19. //hacky but it's assumed to be 1 - 10
  20. if t.Value == 10 {
  21. close(ch)
  22. }
  23. }
  24.  
  25. // Same determines whether the trees
  26. // t1 and t2 contain the same values.
  27. func Same(t1, t2 *tree.Tree) bool {
  28. ch1 := make(chan int)
  29. ch2 := make(chan int)
  30.  
  31. go Walk(t1, ch1)
  32. go Walk(t2, ch2)
  33.  
  34. for {
  35. x, ok := <-ch1
  36. if !ok {
  37. break
  38. }
  39. y, ok := <-ch2
  40. if !ok {
  41. break
  42. }
  43. if x != y {
  44. return false
  45. }
  46. }
  47. return true
  48. }
  49.  
  50. func main() {
  51. fmt.Println(Same(tree.New(1), tree.New(1)))
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement