76 lines
973 B
Go
76 lines
973 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"golang.org/x/tour/tree"
|
|
)
|
|
|
|
func Walk(t *tree.Tree, ch chan int) {
|
|
walk(t, ch)
|
|
close(ch)
|
|
}
|
|
|
|
// walk traverses the tree by the pre-order
|
|
func walk(t *tree.Tree, ch chan int) {
|
|
if t != nil {
|
|
ch <- t.Value
|
|
|
|
walk(t.Left, ch)
|
|
|
|
walk(t.Right, ch)
|
|
}
|
|
|
|
}
|
|
|
|
func Same(t1, t2 *tree.Tree) bool {
|
|
|
|
ch1 := make(chan int)
|
|
ch2 := make(chan int)
|
|
|
|
go Walk(t1, ch1)
|
|
go Walk(t2, ch2)
|
|
|
|
x, y := 0, 0
|
|
ok := true
|
|
for {
|
|
select {
|
|
case x, ok = <-ch1:
|
|
if !ok {
|
|
return true
|
|
}
|
|
y = <-ch2
|
|
if x != y {
|
|
return false
|
|
}
|
|
|
|
case x, ok = <-ch2:
|
|
if !ok {
|
|
fmt.Println("ch2 done")
|
|
fmt.Println(x)
|
|
return true
|
|
}
|
|
fmt.Println("ch2")
|
|
fmt.Println(x)
|
|
y = <-ch1
|
|
fmt.Println("ch1")
|
|
fmt.Println(y)
|
|
if x != y {
|
|
return false
|
|
}
|
|
}
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
func main() {
|
|
|
|
// fmt.Println(Same(tree.New(1), tree.New(1)))
|
|
|
|
t := tree.New(1)
|
|
fmt.Println(Same(t, t))
|
|
|
|
// fmt.Println(Same(tree.New(1), tree.New(2)))
|
|
}
|