在不使用通道的情况下,我可以比较这两棵树是否等价,但使用通道时,我不知道该怎么做.

以下是我使用通道编写的示例代码.

func Walk(t *Tree, ch chan int) {
    if t == nil {
        return
    }
    Walk(t.Left, ch)
    ch <- t.Value
    Walk(t.Right, ch)
}

func Same(t1, t2 *Tree) bool {

    t1Ch := make(chan int)
    t2Ch := make(chan int)

    Walk(t1, t1Ch)
    Walk(t2, t2Ch)
    output := make(chan bool)
    go func() {
        n1 := <-t1Ch
        n2 := <-t2Ch
        output <- n1 == n2
    }()
    return <-output

}

func main() {
    fmt.Println((&root, &root1))
}

注::你可以在这里找到完整的描述https://go.dev/tour/concurrency/7

推荐答案

首先,当你走完树时,你应该关闭你的频道.这可以通过分离递归函数来实现,如下所示:

func Walk(t *tree.Tree, ch chan int) {
    defer close(ch)
    if t != nil {
        ch <- t.Value
        walkRecursively(t.Left, ch)
        walkRecursively(t.Right, ch)
    }
    
}

func walkRecursively(t *tree.Tree, ch chan int) {
    if t != nil {
        ch <- t.Value
        walkRecursively(t.Left, ch)
        walkRecursively(t.Right, ch)
    }
}

现在,相同的()函数可以覆盖两个通道,并知道工作何时完成:

func Same(t1, t2 *tree.Tree) bool {

    // two channels for walking over two trees
    ch1 := make(chan int)
    ch2 := make(chan int)
    
    // two integer slices to capture two results
    sequence1 := []int{}
    sequence2 := []int{}
    
    // two go routines to push values to the channels
    // IMPORTANT! these must be go routines
    go Walk(t1, ch1)
    go Walk(t2, ch2)
    
    // range over the channels to populate the sequence vars
    for n1 := range ch1 {
        sequence1 = append(sequence1, n1)   
    }
    for n2 := range ch2 {
        sequence2 = append(sequence2, n2)   
    }

    // since trees are randomly structured, we sort
    sort.Ints(sequence1)
    sort.Ints(sequence2)

    // slicesAreEqual is a helper function
    return slicesAreEqual(sequence1, sequence2)
}

您的助手函数可能如下所示:

func slicesAreEqual(a, b []int) bool {
    if len(a) != len(b) {
        return false
    }
    for i, v := range a {
        if v != b[i] {
            return false
        }
    }
    return true
}

Go相关问答推荐

Go-Colly:将数据切片为POST请求

带有条件的for循环中缺少RETURN语句

在Golang中Mergesort的递归/并行实现中出现死锁

Go源在Goland(IDEA)中以灰色显示.什么意思?我怎么才能让它恢复正常?

从使用Golang otelmux检测的Otel跟踪中获取trace_id

如何使用 go 读取 RDF xml 文件中的 XML 命名空间属性

死锁 - 所有 goroutine 都处于睡眠状态(即使使用等待组)

生成一个 CSV/Excel,在 Golang 中该列的下拉选项中指定值

使用Dockertest进行Golang SQL单元测试的基本设置

Golang chromedp Dockerfile

如何在 Go 中将 int 转换为包含 complex128 的泛型类型?

Golang:如何在不转义每个动作的情况下呈现模板的模板?

无法将 graphql-ws 连接到 gqlgen

如何匹配两次出现的相同但随机字符串之间的字符

如何使用带有方法的字符串枚举作为通用参数?

转到文本/模板模板:如何根据模板本身的值数组判断值?

使用正则表达式拆分具有相同标题的数据块

传递上下文的最佳方式

GOLANG 如何使用 http.FileServer 从模板目录加载某个 html 文件

为什么 template.ParseFiles() 没有检测到这个错误?