Created
June 24, 2019 23:08
-
-
Save albert-yu/741ab5b7686903d796026a193f392bfd to your computer and use it in GitHub Desktop.
Small exercise comparing binary trees from A Tour of Go
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
// Exercise page can be found at | |
// https://tour.golang.org/concurrency/8 | |
package main | |
import ( | |
"fmt" | |
"golang.org/x/tour/tree" | |
) | |
/* | |
type Tree struct { | |
Left *Tree | |
Value int | |
Right *Tree | |
} | |
*/ | |
func WalkRecur(t *tree.Tree, ch chan int) { | |
if t == nil { | |
return | |
} | |
if t.Left != nil { | |
WalkRecur(t.Left, ch) | |
} | |
ch <- t.Value | |
if t.Right != nil { | |
WalkRecur(t.Right, ch) | |
} | |
} | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
WalkRecur(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 Walk(t1, ch1) | |
go Walk(t2, ch2) | |
i, ok1 := <-ch1 | |
j, ok2 := <-ch2 | |
for { | |
if !ok1 && !ok2 { | |
break | |
} | |
if !ok1 || ! ok2 { | |
return false | |
} | |
if i != j { | |
return false | |
} | |
i, ok1 = <-ch1 | |
j, ok2 = <-ch2 | |
} | |
return true | |
} | |
func main() { | |
ch := make(chan int) | |
go Walk(tree.New(2), ch) | |
for i := range ch { | |
fmt.Println(i) | |
} | |
fmt.Println(Same(tree.New(2), tree.New(2))) | |
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