-
-
Save mckoss/e440d5fc88a151f52a30 to your computer and use it in GitHub Desktop.
Exercise: Equivalent Binary Trees http://tour.golang.org/#70
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"code.google.com/p/go-tour/tree" | |
"fmt" | |
) | |
func main() { | |
ch := make(chan int) | |
go Walk(tree.New(1), ch) | |
for v := range ch { | |
fmt.Println(v) | |
} | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
} | |
func Walk(t *tree.Tree, ch chan<- int) { | |
var walker func(*tree.Tree) | |
walker = func(t *tree.Tree) { | |
for t != nil { | |
walker(t.Left) | |
ch <- t.Value | |
t = t.Right | |
} | |
} | |
walker(t) | |
close(ch) | |
} | |
func Same(t1, t2 *tree.Tree) bool { | |
ch1, ch2 := make(chan int), make(chan int) | |
var v1, v2 int | |
var ok bool | |
go Walk(t1, ch1) | |
go Walk(t2, ch2) | |
for v1 = range ch1 { | |
v2, ok = <-ch2 | |
if !ok || v1 != v2 { | |
return false | |
} | |
} | |
v2, ok = <-ch2 | |
return !ok | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment