Go Tour Exercise: Equivalent Binary Trees

前端 未结 23 1802
攒了一身酷
攒了一身酷 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:21

    This is how I did it, the difference is that you can wrap Walk into anonymous function and defer close(ch) inside it. Thus you have not to define other named recursive function

    package main
    
    import (
        "golang.org/x/tour/tree"
        "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)
    }
    // Same determines whether the trees
    // t1 and t2 contain the same values.
    func Same(t1, t2 *tree.Tree) bool {
        ch1, ch2 := make(chan int), make(chan int)
        go func() {
            defer close(ch1)
            Walk(t1, ch1)
        }()
        go func() {
            defer close(ch2)
            Walk(t2, ch2)
        }()
        for {
            v1, ok1 := <- ch1
            v2, ok2 := <- ch2
            if ok1 != ok2 || v1 != v2 {
                return false
            }
            if !ok1 && !ok2 {
                break
            }
        }
        return true
    }
    
    func main() {
        ch := make(chan int)
        go func () {
            defer close(ch)
            Walk(tree.New(3), ch)
        }()
        for i := range ch {
            fmt.Println(i)
        }
    
        fmt.Println(Same(tree.New(1), tree.New(1)))
        fmt.Println(Same(tree.New(1), tree.New(2)))
        fmt.Println(Same(tree.New(10), tree.New(10)))
    }
    

提交回复
热议问题