From f8c8c05071c66099ef064ef75e59e772b2dd3c43 Mon Sep 17 00:00:00 2001 From: Alex Denes Date: Sat, 1 May 2021 12:11:15 +0000 Subject: [PATCH] Add binary tree ex --- src/go-tour/bintree.go | 57 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/go-tour/bintree.go diff --git a/src/go-tour/bintree.go b/src/go-tour/bintree.go new file mode 100644 index 0000000..077aa61 --- /dev/null +++ b/src/go-tour/bintree.go @@ -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") + } +}