Advertisement
Guest User

Arboles_en_go_con_canales

a guest
May 24th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.29 KB | None | 0 0
  1. package main
  2.  
  3. import "fmt"
  4.  
  5. type Node struct {
  6.     Left  *Node
  7.     Value int
  8.     Right *Node
  9. }
  10.  
  11. func add(node *Node, val int) *Node {
  12.     if node == nil {
  13.         return &Node{Value: val}
  14.     } else if val > node.Value {
  15.         node.Right = add(node.Right, val)
  16.     } else {
  17.         node.Left = add(node.Left, val)
  18.     }
  19.     return node
  20. }
  21.  
  22. func inOrder(node *Node, f func(int)) {
  23.     if node != nil {
  24.         inOrder(node.Left, f)
  25.         f(node.Value)
  26.         inOrder(node.Right, f)
  27.     }
  28. }
  29.  
  30. type Tree struct {
  31.     root   *Node
  32.     length uint
  33. }
  34.  
  35. func (t *Tree) Add(val int) {
  36.     t.root = add(t.root, val)
  37.     t.length++
  38. }
  39.  
  40. func (t *Tree) InOrder(f func(int)) {
  41.     inOrder(t.root, f)
  42. }
  43.  
  44. func check(t1, t2 *Tree) bool {
  45.     if t1.length != t2.length {
  46.         return false
  47.     }
  48.  
  49.     ch1 := make(chan int)
  50.     ch2 := make(chan int)
  51.  
  52.     go t1.InOrder(func(a int) { ch1 <- a })
  53.     go t2.InOrder(func(a int) { ch2 <- a })
  54.  
  55.     for i := uint(0); i < t1.length; i++ {
  56.         if <-ch1 != <-ch2 {
  57.             return false
  58.         }
  59.     }
  60.  
  61.     return true
  62.  
  63. }
  64.  
  65. func main() {
  66.     print := func(a int) {
  67.         fmt.Print(a, " ")
  68.     }
  69.  
  70.     t1 := new(Tree)
  71.     t2 := new(Tree)
  72.  
  73.     for i := 0; i < 10; i++ {
  74.         t1.Add(i + 1)
  75.         t2.Add(10 - i)
  76.     }
  77.  
  78.     t1.InOrder(print)
  79.     fmt.Println()
  80.     t2.InOrder(print)
  81.     fmt.Println()
  82.  
  83.     if check(t1, t2) {
  84.         fmt.Println(":)")
  85.     } else {
  86.         fmt.Println(":(")
  87.     }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement