Skip to content

Instantly share code, notes, and snippets.

@md2perpe
Created January 22, 2018 20:29
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 md2perpe/e9f87f2482a86290196b2065ac4f09b1 to your computer and use it in GitHub Desktop.
Save md2perpe/e9f87f2482a86290196b2065ac4f09b1 to your computer and use it in GitHub Desktop.
package main
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) {
walk(t, ch)
close(ch)
}
func walk(t *tree.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.Tree) bool {
ch1 := make(chan int)
go Walk(t1, ch1)
ch2 := make(chan int)
go Walk(t2, ch2)
for {
n1, ok1 := <-ch1
n2, ok2 := <-ch2
if !ok1 && !ok2 {
return true
}
if ok1 != ok2 || n1 != n2 {
return false
}
}
return true
}
func main() {
t1a := tree.New(1)
fmt.Println(t1a)
t1b := tree.New(1)
fmt.Println(t1b)
t2 := tree.New(2)
fmt.Println(t2)
fmt.Println("t1a == t1b:", Same(t1a, t1b))
fmt.Println("t1a == t2:", Same(t1a, t2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment