Go Tour Exercise: Equivalent Binary Trees

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

    This is my solution. It properly checks for differences in the length of the two sequences.

    package main
    
    import "code.google.com/p/go-tour/tree"
    import "fmt"
    
    func Walk(t *tree.Tree, ch chan int) {
        var walker func (t *tree.Tree)
        walker = func (t *tree.Tree) {
            if t.Left != nil {
                walker(t.Left)
            }
            ch <- t.Value
            if t.Right != nil {
                walker(t.Right)
            }
        }
        walker(t)
        close(ch)
    }
    
    func Same(t1, t2 *tree.Tree) bool {
        chana := make (chan int)
        chanb := make (chan int)
    
        go Walk(t1, chana)
        go Walk(t2, chanb)
    
        for {
            n1, ok1 := <-chana
            n2, ok2 := <-chanb        
            if n1 != n2 || ok1 != ok2 {
                return false
            }
            if (!ok1) {
                break
            }
        }
        return true; 
    }
    

提交回复
热议问题