Skip to content

Instantly share code, notes, and snippets.

@tsyber1an
Created October 21, 2021 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsyber1an/de7c9e73faa9dfcb170a36000a2fa915 to your computer and use it in GitHub Desktop.
Save tsyber1an/de7c9e73faa9dfcb170a36000a2fa915 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) {
walkRecurse(t, ch)
close(ch)
}
func walkRecurse(t *tree.Tree, ch chan int) {
if t.Left != nil {
walkRecurse(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
walkRecurse(t.Right, ch)
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
t1Ch := make(chan int)
t2Ch := make(chan int)
go Walk(t1, t1Ch)
go Walk(t2, t2Ch)
t1Values := map[int]struct{}{}
for v1 := range t1Ch {
if _, seen := t1Values[v1]; !seen {
t1Values[v1] = struct{}{}
}
}
for v2 := range t2Ch {
if _, seen := t1Values[v2]; !seen {
return false
}
}
return true
}
func main() {
t := tree.New(1)
values := make(chan int)
go Walk(t, values)
for v := range values {
fmt.Println(v)
}
t1, t2 := tree.New(1), tree.New(2)
fmt.Println(Same(t1, t2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment