Last active
December 21, 2015 23:18
-
-
Save bpicolo/6381076 to your computer and use it in GitHub Desktop.
A Tour of Go exercises (tour.golang.org)
This file contains hidden or 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
Ex 70: Equivalent Binary Trees | |
***************************************** | |
package main | |
import "code.google.com/p/go-tour/tree" | |
import "fmt" | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int){ | |
//Following tour linearly, so recursive walk instead of using a queue | |
if t == nil{ | |
return | |
} | |
//In order walks will allow us to check most easily | |
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{ | |
ch1 := make(chan int) | |
ch2 := make(chan int) | |
go func(){ | |
/*Since our walk is recursive (Queueless solution and the trees | |
don't have pointers to parents) we make an anonymous | |
go function that closes the channel when all is done. | |
This prevents goroutine deadlock*/ | |
Walk(t1, ch1) | |
close(ch1) | |
}() | |
go func(){ | |
Walk(t2, ch2) | |
close(ch2) | |
}() | |
for{ | |
v1, ok1 := <- ch1 | |
v2, ok2 := <- ch2 | |
if ok1 != ok2 { | |
return false | |
} | |
if v1 != v2{ | |
return false | |
} | |
if ok1 == false && ok2 == false{ | |
return true | |
} | |
} | |
} | |
func main() { | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment