Skip to content

Instantly share code, notes, and snippets.

@brianjester
Last active January 15, 2018 02:27
Show Gist options
  • Save brianjester/cfa14b7a78a00419fb20c8b3b57044cc to your computer and use it in GitHub Desktop.
Save brianjester/cfa14b7a78a00419fb20c8b3b57044cc to your computer and use it in GitHub Desktop.
Working with trees in golang
package main
import "fmt"
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) {
fmt.Println(t)
Climb(t, ch)
close(ch)
}
func Climb(t *tree.Tree, ch chan int) {
if t != nil {
Climb(t.Left, ch)
ch <- t.Value
Climb(t.Right, ch)
}
}
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for {
x1, ok1 := <-ch1
x2, ok2 := <-ch2
switch {
case x1 != x2: //trees value differs
return false
case !ok1 && !ok2: //both are empty
return true
case ok1 != ok2: //trees size differs
return false
default:
//keep going
}
}
}
func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
//Prints out from channel below
for i := range ch {
fmt.Println(i)
}
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