Created
July 20, 2018 14:11
-
-
Save Fykec/c9a2238d34f97e603bc95f752f2231cb to your computer and use it in GitHub Desktop.
Exercise: Equivalent Binary Trees https://tour.golang.org/concurrency/8
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 "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) { | |
if t.Left != nil { | |
Walk(t.Left, ch) | |
} | |
ch <- t.Value | |
if t.Right != nil { | |
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 Walk(t1, ch1) | |
go Walk(t2, ch2) | |
iTotal, jTotal := 0, 0 | |
for index := 1; index <= 20; index++ { | |
select { | |
case i := <-ch1: | |
{ | |
//println(i) | |
iTotal += i | |
} | |
case j := <- ch2: | |
{ | |
//println(j) | |
jTotal += j | |
} | |
} | |
} | |
return iTotal == jTotal | |
} | |
func main() { | |
print(Same(tree.New(2), tree.New(2))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment