Go Tour Exercise: Equivalent Binary Trees

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

    because the question just said the tree just 10 nodes,then following is my answer after read other answers:

    func Walk(t *tree.Tree, ch chan int) {
        defer close(ch)
    
        var walker func(t *tree.Tree)
        walker = func(t *tree.Tree) {
            if t == nil {
                return
            }
    
            walker(t.Left)
            ch <- t.Value
            walker(t.Right)
        }
        walker(t)
    }
    
    func Same(t1, t2 *tree.Tree) bool {
        ch1, ch2 := make(chan int), make(chan int)
        go Walk(t1, ch1)
        go Walk(t2, ch2)
    
        for range make([]struct{}, 10) {
            if <-ch1 != <-ch2 {
                return false
            }
        }
        return true
    }
    

提交回复
热议问题