Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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) {
- if t.Left != nil {
- go Walk(t.Left, ch)
- }
- ch <- t.Value
- if t.Right != nil {
- go Walk(t.Right, ch)
- }
- //hacky but it's assumed to be 1 - 10
- if t.Value == 10 {
- 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 Walk(t1, ch1)
- go Walk(t2, ch2)
- for {
- x, ok := <-ch1
- if !ok {
- break
- }
- y, ok := <-ch2
- if !ok {
- break
- }
- if x != y {
- return false
- }
- }
- return true
- }
- func main() {
- fmt.Println(Same(tree.New(1), tree.New(1)))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement