SHARE
TWEET

Untitled

a guest Jul 17th, 2019 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "golang.org/x/tour/tree"
  6. )
  7.  
  8. type Tree struct {
  9.     Left  *Tree
  10.     Value int
  11.     Right *Tree
  12. }
  13.  
  14. // Walk walks the tree t sending all values
  15. // from the tree to the channel ch.
  16. func Walk(t *tree.Tree, ch chan int) {
  17.     if t.Left != nil {
  18.         Walk(t.Left, ch)
  19.     }
  20.     ch <- t.Value
  21.  
  22.     if t.Right != nil {
  23.         Walk(t.Right, ch)
  24.     }
  25. }
  26.  
  27. // Same determines whether the trees
  28. // t1 and t2 contain the same values.
  29. func Same(t1, t2 *tree.Tree) bool {
  30.     ch1, ch2 := make(chan int, 10), make(chan int, 10)
  31.     Walk(t1, ch1)
  32.     Walk(t2, ch2)
  33.     for i := 0; i < 10; i++ {
  34.         x, y := <-ch1, <-ch2
  35.         if x != y {
  36.             return false
  37.         }
  38.     }
  39.     return true
  40. }
  41.  
  42. func main() {
  43.     ch := make(chan int, 10)
  44.     go Walk(tree.New(1), ch)
  45.     for i := 0; i < 10; i++ {
  46.         fmt.Println(<-ch)
  47.     }
  48.     fmt.Println(Same(tree.New(1), tree.New(2)))
  49. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top