Last active
September 8, 2015 00:32
-
-
Save smilingleo/e57238956e706e0d5870 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" | |
"fmt" | |
) | |
// 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) | |
walk = func(t *tree.Tree) { | |
if t.Left != nil { | |
walk(t.Left) | |
} | |
ch <- t.Value | |
if t.Right != nil { | |
walk(t.Right) | |
} | |
} | |
walk(t) | |
close(ch) | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
ch1, ch2 := make(chan int), make(chan int) | |
go Walk(t1, ch1) | |
go Walk(t2, ch2) | |
for { | |
v1, ok1 := <- ch1 | |
v2, ok2 := <- ch2 | |
// fmt.Printf("v1, ok1 = %d, %s v2, ok2 = %d, %s", v1, ok1, v2, ok2) | |
if v1 != v2 || ok1 != ok2 { | |
return false | |
} | |
if ok1 == ok2 && !ok1 { | |
break | |
} | |
} | |
return true | |
} | |
func main() { | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(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