Go Tour Exercise: Equivalent Binary Trees

前端 未结 23 1847
攒了一身酷
攒了一身酷 2020-12-12 23:39

I am trying to solve equivalent binary trees exercise on go tour. Here is what I did;

package main

import \"tour/tree\"
import \"fmt\"

// Walk walks the tr         


        
23条回答
  •  情书的邮戳
    2020-12-13 00:25

    A clear answer:

    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 {
            return
        }
        Walk(t.Left, ch)
        ch <- t.Value
        Walk(t.Right, ch)
    }
    
    func WalkATree(t *tree.Tree, ch chan int) {
        Walk(t, ch)
        close(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 WalkATree(t1, ch1)
        go WalkATree(t2, ch2)
        var v1, v2 int
        var ok1, ok2 bool
        for {
            v1, ok1 = <- ch1
            v2, ok2 = <- ch2
            if !ok1 && !ok2 {
                return true
            }
            if !ok1 && ok2 || ok1 && !ok2 {
                return false
            }
            if v1 != v2 {
                return false
            }
        }
    }
    
    func main() {
        fmt.Println(Same(tree.New(1), tree.New(1)))
    }
    

提交回复
热议问题