Go Tour Exercise: Equivalent Binary Trees

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

    Here's the solution I came up with :

    func Walker(t *tree.Tree, ch chan int){
        if t==nil {return}
        Walker(t.Left,ch)
        ch<-t.Value
        Walker(t.Right,ch)   
    }
    
    func Walk(t *tree.Tree, ch chan int){
       Walker(t,ch)
       close(ch)
    }
    
    func Same(t1, t2 *tree.Tree) bool{
        ch:=make(chan int)
        dh:=make(chan int)
        go Walk(t1,ch)
        go Walk(t2,dh)
    
        for i:=range ch {
            j,ok:=<-dh
            if(i!=j||!ok)  {return false} 
        }
    
        return true
    }
    

提交回复
热议问题