I am trying to solve equivalent binary trees exercise on go tour. Here is what I did;
package main
import \"tour/tree\"
import \"fmt\"
// Walk walks the tr
Here's a solution that doesn't depend on differing tree lengths, neither does it depend on traversal order:
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) {
var walk func(*tree.Tree)
walk = func(tr *tree.Tree) {
if tr == nil {
return
}
walk(tr.Left)
ch <- tr.Value
walk(tr.Right)
}
walk(t)
close(ch)
}
func merge(ch chan int, m map[int]int) {
for i := range ch {
count, ok := m[i]
if ok {
m[i] = count + 1
} else {
m[i] = 1
}
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int, 100)
ch2 := make(chan int, 100)
m := make(map[int]int)
go Walk(t1, ch1)
go Walk(t2, ch2)
merge(ch1, m)
merge(ch2, m)
for _, count := range m {
if count != 2 {
return false
}
}
return true
}