Last active
August 29, 2015 14:00
-
-
Save gbarrancos/11260237 to your computer and use it in GitHub Desktop.
Equivalent Binary Trees Exercise from Golang Tour
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" | |
) | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
InOrderTraversal(t, ch) | |
close(ch) | |
} | |
func InOrderTraversal(t *tree.Tree, ch chan int) { | |
if t.Left != nil { | |
InOrderTraversal(t.Left, ch) | |
} | |
ch <- t.Value | |
if t.Right != nil { | |
InOrderTraversal(t.Right, ch) | |
} | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
chan1 := make(chan int) | |
chan2 := make(chan int) | |
go Walk(t1, chan1) | |
go Walk(t2, chan2) | |
for v1 := range chan1 { | |
v2 := <- chan2 | |
if v1 != v2 { | |
return false | |
} | |
} | |
return true | |
} | |
func main() { | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Still missing a way to signal when both trees were entirely "walked" @ line 33