Advertisement
fenixD3

Exercise: Equivalent Binary Trees

Jun 17th, 2024
886
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.11 KB | None | 0 0
  1. package main
  2.  
  3. import "golang.org/x/tour/tree"
  4. import "fmt"
  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.     var traverse func(t *tree.Tree)
  10.     traverse = func(t *tree.Tree) {
  11.         if t == nil {
  12.             return
  13.         }
  14.         traverse(t.Left)
  15.         ch <- t.Value
  16.         traverse(t.Right)
  17.     }
  18.     traverse(t)
  19.     close(ch)
  20. }
  21.  
  22. // Same determines whether the trees
  23. // t1 and t2 contain the same values.
  24. func Same(t1, t2 *tree.Tree) bool {
  25.     ch_1, ch_2 := make(chan int), make(chan int)
  26.     go Walk(t1, ch_1)
  27.     go Walk(t2, ch_2)
  28.     for first := range ch_1 {
  29.         select {
  30.         case second := <-ch_2:
  31.             if first != second {
  32.                 return false
  33.             }
  34.         default:
  35.             break
  36.         }
  37.  
  38.         /*      second := <-ch_2
  39.                 if first != second {
  40.                     return false
  41.                 }*/
  42.     }
  43.     /*  if _, ok := <-ch_2; ok {
  44.         return false
  45.     }*/
  46.     return true
  47. }
  48.  
  49. func main() {
  50.     fmt.Println(Same(tree.New(1), tree.New(1)))
  51.     fmt.Println(Same(tree.New(1), tree.New(2)))
  52.     fmt.Println(Same(tree.New(2), tree.New(1)))
  53.  
  54.     t1 := tree.New(2)
  55.     t2 := tree.New(3)
  56.     fmt.Println(t1)
  57.     fmt.Println(t2)
  58.     fmt.Println(Same(t1, t2))
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement