Add binary tree ex

This commit is contained in:
Alex D. 2021-05-01 12:11:15 +00:00
parent bb8314994b
commit f8c8c05071
Signed by: caskd
GPG Key ID: F92BA85F61F4C173
1 changed files with 57 additions and 0 deletions

57
src/go-tour/bintree.go Normal file
View File

@ -0,0 +1,57 @@
package main
import "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 {
close(ch)
return
}
lolch := make(chan int)
lorch := make(chan int)
go Walk(t.Left, lolch)
go Walk(t.Right, lorch)
for i := range lolch {
ch <-i
}
ch <-t.Value
for i := range lorch {
ch <-i
}
close(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)
for {
x, okx := <-t1ch
y, oky := <-t2ch
if !okx && !oky {
return true
} else if x == y {
continue
}
return false
}
}
func main() {
t1 := tree.New(1)
t2 := tree.New(2)
if !Same(t1, t1) || Same(t1, t2) {
fmt.Println("Something went wrong")
}
}