Skip to content

Instantly share code, notes, and snippets.

@zainfathoni
Last active April 24, 2022 17:18
Show Gist options
  • Save zainfathoni/423935b1a5036019f36a8e949bc6ecc0 to your computer and use it in GitHub Desktop.
Save zainfathoni/423935b1a5036019f36a8e949bc6ecc0 to your computer and use it in GitHub Desktop.
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) {
Recurse(t, ch)
close(ch)
}
func Recurse(t *tree.Tree, ch chan int) {
if t != nil {
Recurse(t.Left, ch)
ch <- t.Value
Recurse(t.Right, ch)
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
v1 := make(chan int)
v2 := make(chan int)
go Walk(t1, v1)
go Walk(t2, v2)
for val := range v1 {
if val != <-v2 {
return false
}
}
return true
}
func Show(ch chan int) {
for v := range ch {
fmt.Println(v)
}
}
func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
Show(ch)
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
@cominging
Copy link

Would Same() return the wrong answer if given a tree ((1) 2 (0)) and another tree ((1) 2) because a closed channel will return zero value for the channel type?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment