Add binary tree ex
This commit is contained in:
parent
bb8314994b
commit
f8c8c05071
|
@ -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")
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue