Skip to content

Instantly share code, notes, and snippets.

@mrfade
Created October 22, 2022 23:21
Show Gist options
  • Save mrfade/e31ba217b3e27a44fab7c972aaa0a496 to your computer and use it in GitHub Desktop.
Save mrfade/e31ba217b3e27a44fab7c972aaa0a496 to your computer and use it in GitHub Desktop.
A Tour of Go Exercise: Equivalent Binary Trees
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
if t.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
Walk(t.Right, 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 func() {
Walk(t1, ch1)
close(ch1)
}()
go func() {
Walk(t2, ch2)
close(ch2)
}()
for {
v1, ok1 := <-ch1
v2, ok2 := <-ch2
if ok1 != ok2 || v1 != v2 {
return false
}
if ok1 == false || ok2 == false {
break
}
}
return true
}
func main() {
fmt.Println("Same(tree.New(1), tree.New(1)) ->", Same(tree.New(1), tree.New(1)))
fmt.Println("Same(tree.New(1), tree.New(2)) ->", Same(tree.New(1), tree.New(2)))
fmt.Println("Same(tree.New(2), tree.New(1)) ->", Same(tree.New(2), tree.New(1)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment