Skip to content

Instantly share code, notes, and snippets.

@noroutine
Last active February 16, 2016 08:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noroutine/c32eb6a0d8b8dc428683 to your computer and use it in GitHub Desktop.
Save noroutine/c32eb6a0d8b8dc428683 to your computer and use it in GitHub Desktop.
go tree walk
package main
import (
"math/rand"
"fmt"
"time"
)
type Tree struct {
Left *Tree
Value int
Right *Tree
}
func (root *Tree) randTree(N int, values chan int) (*Tree) {
left_branch_N := rand.Intn(N)
right_branch_N := N - 1 - left_branch_N
if left_branch_N > 0 {
root.Left = &Tree{}
root.Left.randTree(left_branch_N, values)
}
root.Value = <- values
if right_branch_N > 0 {
root.Right = &Tree{}
root.Right.randTree(right_branch_N, values)
}
return root
}
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *Tree, ch chan int) {
if t == nil {
return
}
Walk(t.Left, ch)
ch <- t.Value
Walk(t.Right, ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *Tree) bool {
return false
}
func main() {
var values chan int = make(chan int)
go func(ch chan int) {
var i int = 1
for {
ch <- 2*i
i++
}
}(values)
var tree1 *Tree = (&Tree{}).randTree(10, values)
var tree2 *Tree = (&Tree{}).randTree(10, values)
var out_ch chan int = make(chan int)
go func(ch chan int) {
for value := range ch {
fmt.Println(value)
}
}(out_ch)
Walk(tree1, out_ch)
time.Sleep(1000 * time.Millisecond)
Walk(tree2, out_ch)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment