Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am following the Golang tour and I have been asked to build a couple of functions to manipulate binary trees.

My code runs as expected, but I would like to know if I could further improve my code. I'm looking for improvements regarding the algorithm and mainly the use of go routines. As the point of this exercise is to mainly work with go routines I would like to know if I could further add more go routines and to improve the concurrent design of this app.

You can try it in the go playground.

package main

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

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

}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    t1Slice := make([]int,1)
    t1ch := make(chan int)
    t2Slice := make([]int,1)
    t2ch := make(chan int)
    go func(){
        Walk(t1,t1ch)
        close(t1ch)
    }()
    go func(){
        Walk(t2,t2ch)
        close(t2ch)
    }()
    for j := range t1ch{
        h := append(t1Slice, j)
        t1Slice = h
    }
    for i:= range t2ch{
        o := append(t2Slice,i)   
        t2Slice = o
    }
    for z := 0; z < len(t1Slice); z++ {
        if t1Slice[z] != t2Slice[z] {
            return false   
        }
    }
    return true

}

func main() {
    ch := make(chan int, 5)
    go func() {
        Walk(tree.New(1),ch) 
        close(ch)
    }()
    for j := range ch {
        fmt.Println(j)
    }

    fmt.Println(Same(tree.New(1), tree.New(1)))
    fmt.Println(Same(tree.New(1), tree.New(2)))

}
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.