Skip to content

Instantly share code, notes, and snippets.

@jcolson
Created February 24, 2020 10:30
Show Gist options
  • Save jcolson/000df324c045ba2d0182fc9e1c9a6f53 to your computer and use it in GitHub Desktop.
Save jcolson/000df324c045ba2d0182fc9e1c9a6f53 to your computer and use it in GitHub Desktop.
golang tour tree exercise
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) {
// fmt.Printf("in walk\n")
for {
ch <- t.Value
if t.Left != nil {
Walk(t.Left, ch)
}
if t.Right != nil {
Walk(t.Right, ch)
}
break
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
c1 := make(chan int)
go Walk(t1, c1)
go Walk(t2, c1)
m := make(map[int]bool)
for i1 := 0; i1 < 20; i1++ {
r1 := <-c1
_, ok := m[r1]
if ok {
delete(m, r1)
} else {
m[r1] = true
}
}
return len(m) == 0
}
func main() {
theSame := Same(tree.New(1), tree.New(2))
fmt.Printf("the tree's are the same? %v\n", theSame)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment