Go Tour Exercise: Equivalent Binary Trees

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

    You got it almost right, there's no need to use the select statement because you will go through the default case too often, here's my solution that works without needing to count the number of nodes in the tress:

    func Same(t1, t2 *tree.Tree) bool {
        ch1, ch2 := make(chan int), make(chan int)
        go Walk(t1, ch1)
        go Walk(t2, ch2)
        for i := range ch1 {
            j, more := <-ch2
            if more {
                if i != j { return false }
            } else { return false }
        }
    
        return true
    }
    

提交回复
热议问题