Advertisement
stillysmag

tour.golang.org/concurrency/8

Apr 20th, 2021
1,013
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.09 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.   "golang.org/x/tour/tree"
  5.   "fmt"
  6. )
  7.  
  8. func Walk(name string, t *tree.Tree, ch chan int) {
  9.   if t.Left != nil {
  10.     Walk(name, t.Left, ch)
  11.   }
  12.   fmt.Println("Walk", name, t.Value)
  13.   ch <- t.Value
  14.   if t.Right != nil {
  15.     Walk(name, t.Right, ch)
  16.   }
  17. }
  18. var tree1 = tree.Tree{
  19.   Left: &tree.Tree{
  20.     Value: 1,
  21.     Right: &tree.Tree{
  22.       Value: 2,
  23.     },
  24.   },
  25.   Value: 3,
  26.   Right: &tree.Tree{
  27.     Left: &tree.Tree{
  28.       Value: 5,
  29.     },
  30.     Value: 8,
  31.   },
  32. }
  33. var tree2 = tree.Tree{
  34.   Left: &tree.Tree{
  35.     Left: &tree.Tree{
  36.       Value: 1,
  37.       Right: &tree.Tree{
  38.         Value: 2,
  39.       },
  40.     },
  41.     Value: 3,
  42.     Right: &tree.Tree{
  43.       Value: 5,
  44.     },
  45.   },
  46.   Value: 8,
  47. }
  48.  
  49. func Same(t1, t2 *tree.Tree) bool {
  50.   var ch1 = make(chan int, 1)
  51.   go Walk("t1", t1, ch1)
  52.  
  53.   var ch2 = make(chan int, 1)
  54.   go Walk("t2", t2, ch2)
  55.  
  56.   for i:= 0; i<5; i++ {
  57.     v1, v2 := <-ch1, <-ch2
  58.     if v1 != v2 {
  59.       return false
  60.     }
  61.   }
  62.   return true
  63. }
  64. func main() {
  65.   result := Same(&tree1, &tree2)
  66.   fmt.Println("result", result)
  67. }
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement