Go Tour Exercise: Equivalent Binary Trees

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

    Here's a solution that doesn't depend on differing tree lengths, neither does it depend on traversal order:

    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) {
        var walk func(*tree.Tree)
        walk = func(tr *tree.Tree) {
            if tr == nil {
                return
            }
    
            walk(tr.Left)
            ch <- tr.Value
            walk(tr.Right)
        }
    
        walk(t)
        close(ch)
    }
    
    func merge(ch chan int, m map[int]int) {
        for i := range ch {
            count, ok := m[i]
            if ok {
                m[i] = count + 1
            } else {
                m[i] = 1
            }
        }
    }
    
    // Same determines whether the trees
    // t1 and t2 contain the same values.
    func Same(t1, t2 *tree.Tree) bool {
        ch1 := make(chan int, 100)
        ch2 := make(chan int, 100)
        m := make(map[int]int)
    
        go Walk(t1, ch1)
        go Walk(t2, ch2)
    
        merge(ch1, m)
        merge(ch2, m)
    
        for _, count := range m {
            if count != 2 {
                return false
            }
        }
    
        return true
    }
    

提交回复
热议问题