Created
December 14, 2015 18:39
-
-
Save talonx/21caa0bf7caa527f84b5 to your computer and use it in GitHub Desktop.
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) { | |
if t == nil { | |
return | |
} | |
Walk(t.Left, ch) | |
ch <- t.Value | |
Walk(t.Right, ch) | |
} | |
func WalkAndClose(t *tree.Tree, ch chan int) { | |
Walk(t, ch) | |
close(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 WalkAndClose(t1, ch1) | |
go WalkAndClose(t2, ch2) | |
for { | |
v1, ok1 := <- ch1 | |
v2, ok2 := <- ch2 | |
if ok1 != ok2 { | |
return false | |
} | |
if !ok1 && !ok2 { | |
return true | |
} | |
if v1 != v2 { | |
return false | |
} | |
} | |
return true | |
} | |
func testWalk(t *tree.Tree) { | |
ch := make(chan int) | |
go Walk(t, ch) | |
for v := range ch { | |
fmt.Println(v) | |
} | |
} | |
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