Created
April 7, 2012 18:11
-
-
Save jordanorelli/2331060 to your computer and use it in GitHub Desktop.
golang tour exercise 68
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
package main | |
import ( | |
"fmt" | |
"sort" | |
"tour/tree" | |
) | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
var inner func(*tree.Tree, chan int) | |
inner = func(t *tree.Tree, ch chan int) { | |
if t == nil { | |
return | |
} | |
ch <- t.Value | |
inner(t.Left, ch) | |
inner(t.Right, ch) | |
} | |
inner(t, ch) | |
close(ch) | |
} | |
func collect(t *tree.Tree) []int { | |
c := make(chan int) | |
var vals []int | |
go Walk(t, c) | |
for val := range c { | |
vals = append(vals, val) | |
} | |
return vals | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
val1 := collect(t1) | |
val2 := collect(t2) | |
if len(val1) != len(val2) { | |
return false | |
} | |
sort.Ints(val1) | |
sort.Ints(val2) | |
for i := range val1 { | |
if val1[i] != val2[i] { 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