Golang Binary Search Tree Exercise
A sample solution for the concurrency exercise to compare binary search trees.
package main import "golang.org/x/tour/tree" import "fmt" //This sample covers Exercise: Equivalent Binary Trees /* Reference: type Tree struct { Left *Tree Value int Right *Tree } */ // Walk walks the tree t sending all values // from the tree to the channel ch. func Walk(t *tree.Tree, ch chan int) { var walker func(t *tree.Tree) //make a separate synchronous sub-function here so we know when it's finished //so that we can close the channel walker = func(t *tree.Tree) { if(t == nil) { return } walker(t.Left) ch <- t.Value walker(t.Right) } walker(t) 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 { val1, ok1 := <- ch1 val2, ok2 := <- ch2 //if the values dont match and the channels contain different amounts of data if val1 != val2 || ok1 != ok2 { return false } //stop when the channel is closed if !ok1 { break } } return true } func main() { fmt.Println(Same(tree.New(1), tree.New(1))) fmt.Println(Same(tree.New(1), tree.New(2))) fmt.Println(Same(tree.New(2), tree.New(2))) }

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Download this code in plain text format here