Last active
February 26, 2018 20:10
-
-
Save abackstrom/643815185319d6481e931ac6de9a86e3 to your computer and use it in GitHub Desktop.
My solution for Go Tour Concurrency Exercise "Equivalent Binary Trees"
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" | |
"golang.org/x/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 walk func(t *tree.Tree, ch chan int) | |
walk = func(t *tree.Tree, ch chan int) { | |
if t == nil { | |
return | |
} | |
walk(t.Left, ch) | |
ch <- t.Value | |
walk(t.Right, ch) | |
} | |
walk(t, ch) | |
close(ch) | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
c1, c2 := make(chan int), make(chan int) | |
go Walk(t1, c1) | |
go Walk(t2, c2) | |
for v := range c1 { | |
if v != <-c2 { | |
return false | |
} | |
} | |
return true | |
} | |
func main() { | |
fmt.Printf("1=1: %v\n", Same(tree.New(1), tree.New(1))) | |
fmt.Printf("1=2: %v\n", 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