Go Tour Exercise: Equivalent Binary Trees

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

    Here's my solution, without the defer magic. I thought this would be a bit easier to read, so it would worth sharing :)

    Bonus: This version actually solves the problem in the tour's exercise and gives proper results.

    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) {
        walkRecursive(t, ch)
        close(ch)
    }
    
    func walkRecursive(t *tree.Tree, ch chan int) {
        if t != nil {
            walkRecursive(t.Left, ch)
            ch <- t.Value
            walkRecursive(t.Right, ch)
        }
    }
    
    // Same determines whether the trees
    // t1 and t2 contain the same values.
    func Same(t1, t2 *tree.Tree) bool {
        var br bool
        ch1, ch2 := make(chan int), make(chan int)
        go Walk(t1, ch1)
        go Walk(t2, ch2)
    
        for i:= range ch1 {
            if i == <-ch2 {
                br = true
            } else {
                br = false
                break
            }
        }
        return br
    }
    
    func main() {
        ch := make(chan int)
        go Walk(tree.New(1), ch)
    
        for i := range ch {
            fmt.Println(i)
        }
    
        fmt.Println(Same(tree.New(1), tree.New(2)))
        fmt.Println(Same(tree.New(1), tree.New(1)))
        fmt.Println(Same(tree.New(2), tree.New(1)))
    }
    

    So the output is as follows:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    false
    true
    false
    

提交回复
热议问题