Erwin
2011-10-17 19:56:34 UTC
Hello peoples,
I'm working my way through the tour online, which I find an excellent idea,
great way to learn, hands on!
I wondered if I could solve the binary tree exercise so that it would handle
trees of unknown size, and this is what I came up with, is there a cleaner
way?
Or more efficient?
package main
import (
"fmt"
"tour/tree"
)
// inorder depth-first tree traversal
func Walk(t *tree.Tree, ch chan int) {
if t.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Value // process node
if t.Right != nil {
Walk(t.Right, ch)
}
}
// walk the full tree, close output channel when done
func FullWalk(t *tree.Tree, ch chan int) {
Walk(t, ch)
close(ch)
}
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
go FullWalk(t1, ch1)
ch2 := make(chan int)
go FullWalk(t2, ch2)
for {
v1, ok1 := <-ch1
v2, ok2 := <-ch2
if !ok1 && !ok2 { // no more nodes in trees
break
}
if ok1 != ok2 { // trees with different number of nodes
return false
}
if v1 != v2 {
return false
}
}
return true
}
func main() {
fmt.Println("Trees equivalent?", Same(tree.New(1), tree.New(2)))
}
I'm working my way through the tour online, which I find an excellent idea,
great way to learn, hands on!
I wondered if I could solve the binary tree exercise so that it would handle
trees of unknown size, and this is what I came up with, is there a cleaner
way?
Or more efficient?
package main
import (
"fmt"
"tour/tree"
)
// inorder depth-first tree traversal
func Walk(t *tree.Tree, ch chan int) {
if t.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Value // process node
if t.Right != nil {
Walk(t.Right, ch)
}
}
// walk the full tree, close output channel when done
func FullWalk(t *tree.Tree, ch chan int) {
Walk(t, ch)
close(ch)
}
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
go FullWalk(t1, ch1)
ch2 := make(chan int)
go FullWalk(t2, ch2)
for {
v1, ok1 := <-ch1
v2, ok2 := <-ch2
if !ok1 && !ok2 { // no more nodes in trees
break
}
if ok1 != ok2 { // trees with different number of nodes
return false
}
if v1 != v2 {
return false
}
}
return true
}
func main() {
fmt.Println("Trees equivalent?", Same(tree.New(1), tree.New(2)))
}