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:33

    That's how I did it using Inorder Traversal

    package main
    
    import (
        "fmt"
        "golang.org/x/tour/tree"
    )
    
    // 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 {
            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 {
        c1, c2 := make(chan int), make(chan int)
        go Walk(t1, c1)
        go Walk(t2, c2)
        if <-c1 == <-c2 {
            return true
        } else {
            return false
        }
    }
    
    func main() {
        t1 := tree.New(1)
        t2 := tree.New(8)
        fmt.Println("the two trees are same?", Same(t1, t2))
    }
    

提交回复
热议问题