最佳答案
我试图解决 等效二叉树等效二叉树练习在去旅游。这里是我所做的;
package main
import "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.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Value
if 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)
ch2 := make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for k := range ch1 {
select {
case g := <-ch2:
if k != g {
return false
}
default:
break
}
}
return true
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
然而,我无法找到如何信号,如果没有更多的元素留在树上。我不能在 Walk()
上使用 close(ch)
,因为它会在发送所有值之前关闭通道(因为是递归的)有人能帮我一把吗?