SHARE
TWEET

Untitled

a guest Jan 18th, 2020 61 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. func dfs(t *tree.Tree, ch chan int) {
  9.     if (t == nil) { return }
  10.  
  11.     dfs(t.Left, ch)
  12.     ch <- t.Value
  13.     dfs(t.Right, ch)
  14. }
  15.  
  16. func Walk(t *tree.Tree, ch chan int) {
  17.     dfs(t, ch)
  18.     close(ch)
  19. }
  20.  
  21. func Same(t1, t2 *tree.Tree) bool {
  22.     ch1 := make(chan int)
  23.     ch2 := make(chan int)
  24.     go Walk(t1, ch1)
  25.     go Walk(t2, ch2)
  26.  
  27.     var f func(ch1 chan int, ch2 chan int) bool
  28.     f = func(ch1 chan int, ch2 chan int) bool {
  29.         v1, ok1 := <-ch1
  30.         v2, ok2 := <-ch2
  31.  
  32.         if (!ok1 || !ok2) {
  33.             return ok1 == ok2  
  34.         }
  35.         return v1 == v2 && f(ch1, ch2)
  36.     }
  37.  
  38.     return f(ch1, ch2)
  39. }
  40.  
  41. func main() {
  42.     t1 := tree.New(1)
  43.     t2 := tree.New(1)
  44.     fmt.Println(Same(t1, t2))
  45. }
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