A Tour of Go 69 Exercise: Equivalent Binary Trees

演習: Walk 関数を実装、 Same 関数をテストする。

 またまた、答え見た><


ってか、チャネルの戻り値にtrue/false帰ってくること、どこか書いてた?

package main

import (
    "code.google.com/p/go-tour/tree"
    "fmt"
    )

func walkImpl(t *tree.Tree, ch chan int){
    if t.Left != nil {
        walkImpl(t.Left, ch)
    }
    ch <- t.Value
    if t.Right != nil {
        walkImpl(t.Right, ch)
    }
}
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int){
    walkImpl(t,ch)
    close(ch)
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    w1,w2 := make(chan int), make(chan int)
    go Walk(t1, w1)
    go Walk(t2, w2)
    
    for {
        v1, ok1 := <-w1
        v2, ok2 := <-w2
        
        fmt.Println(v1,v2)
        
        if v1 != v2 || ok1 != ok2 {
            return false
        }
        if !ok1 {
            fmt.Println(ok1)
            break
        }
    }
    
    return true
}

func sameHelper(t1, t2 *tree.Tree) {
    fmt.Println(t1)
    fmt.Println(t2)
    
    if Same(t1,t2) {
        fmt.Println("equal")
    } else {
        fmt.Println("not equal")
    }
}

func main() {
    c := make(chan int)
    go Walk(tree.New(1), c)
    //go func() {
        for v := range c {
    		fmt.Println(v)
    	}
    //}()
    
    t1,t2 := tree.New(1), tree.New(1)
    sameHelper(t1, t1)
    sameHelper(t1, t2)
	t1,t2 = tree.New(1), tree.New(2)
    sameHelper(t1, t2)
}