Skip to content

Instantly share code, notes, and snippets.

@e1himself
Created January 31, 2015 21:16
Show Gist options
  • Save e1himself/7514e79accbeae256b93 to your computer and use it in GitHub Desktop.
Save e1himself/7514e79accbeae256b93 to your computer and use it in GitHub Desktop.
Tour of Go: Exercise: Equivalent Binary Trees
package main
import (
"code.google.com/p/go-tour/tree"
"fmt"
)
// Walk walks the tree t sending all values (sorted ascending)
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
if t.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
Walk(t.Right, ch)
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
go Walk(t1, ch1) // ch1 will receive all values from tree 1 (sorted)
go Walk(t2, ch2) // ch2 will receive all values from tree 2 (sorted)
for i := 0; i<10; i++ { // task clearly says it's always 10 items in tree
// all pairs should match
if <- ch1 != <- ch2 { // if not matches
return false // trees are not equivalent
}
}
return true // if we get here: trees are equivalent
}
func main() {
fmt.Println("1)", Same(tree.New(1), tree.New(1)))
fmt.Println("2)", Same(tree.New(1), tree.New(2)))
}
1) true
2) false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment