Member-only story

Exercise: Equivalent Binary Trees in Golang

Simplify Complexity
1 min readMay 15, 2021

From Tour of Go

package mainimport "golang.org/x/tour/tree"
import "fmt"
// 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 == nil {
return
}
if t.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Valueif 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, 10)
ch2 := make(chan int, 10)
Walk(t1, ch1)
Walk(t2, ch2)
for i := 0; i < 10; i++ {
x := <-ch1
y := <-ch2
if x != y {
return false
}
}
return true
}
func main() {
t1 := tree.New(1)
t2 := tree.New(1)
fmt.Println(Same(t1, t2))// ch := make(chan int, 10)// go Walk(testTree, ch)}

References

  1. https://pkg.go.dev/golang.org/x/tour/tree?utm_source=godoc#Tree
  2. https://tour.golang.org/concurrency/8

--

--

Simplify Complexity
Simplify Complexity

Written by Simplify Complexity

Golang, Distributed Systems, File Systems, Python, C/C++, Linux

No responses yet