登录
首页 >  Golang >  Go问答

比较 Golang 中两棵树是否相等的 goroutine 方法

来源:stackoverflow

时间:2024-02-08 23:51:23 166浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《比较 Golang 中两棵树是否相等的 goroutine 方法》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

问题内容

如果不使用通道,我可以比较两棵树是否等效,但使用通道时,我无法弄清楚该怎么做。

这是我使用通道编写的示例代码。

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)
    }
}

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

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
}

以上就是《比较 Golang 中两棵树是否相等的 goroutine 方法》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>