Skip to content

Instantly share code, notes, and snippets.

@danx12
Created March 9, 2019 21:39
Show Gist options
  • Save danx12/e59bd805730190f598b34eb9d7e797d7 to your computer and use it in GitHub Desktop.
Save danx12/e59bd805730190f598b34eb9d7e797d7 to your computer and use it in GitHub Desktop.
Exercise: Equivalent Binary Trees - A Tour of Go
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
func RecursiveWalk(t *tree.Tree, ch chan int) {
if t.Left != nil {
RecursiveWalk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
RecursiveWalk(t.Right, ch)
}
return
}
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
RecursiveWalk(t, ch)
close(ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for ;; {
v1, ok1 := <- ch1
v2, ok2 := <- ch2
if(!ok1 || !ok2) {
break
}
if (v1 != v2) {
return false
}
}
return true
}
func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
for v := range ch {
fmt.Println(v)
}
fmt.Println(Same(tree.New(1),tree.New(2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment