Instantly share code, notes, and snippets.

# kaipakartik/tree.go

Created December 25, 2013 07:00
Show Gist options
• Save kaipakartik/8120855 to your computer and use it in GitHub Desktop.
Exercise: Equivalent Binary Trees
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
 package main import ( "code.google.com/p/go-tour/tree" "fmt" ) // Walk walks the tree t sending all values // from the tree to the channel ch. func Walk(t *tree.Tree, ch chan int) { WalkRecursive(t, ch) close(ch) } func WalkRecursive(t *tree.Tree, ch chan int) { if t != nil { WalkRecursive(t.Left, ch) ch <- t.Value WalkRecursive(t.Right, ch) } } // Same determines whether the trees // t1 and t2 contain the same values. func Same(t1, t2 *tree.Tree) bool { ch1, ch2 := make(chan int), make(chan int) go Walk(t1, ch1) go Walk(t2, ch2) for { n1, ok1 := <- ch1 n2, ok2 := <- ch2 if ok1 != ok2 || n1 != n2 { return false } if !ok1 { break; } } return true } func main() { ch := make(chan int) go Walk(tree.New(1), ch) fmt.Println(Same(tree.New(1), tree.New(2))) fmt.Println(Same(tree.New(1), tree.New(1))) fmt.Println(Same(tree.New(2), tree.New(1))) }

```package main

import (
"golang.org/x/tour/tree"
"fmt"
)

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
if t.Left != nil {
Walk(t.Left, ch)
}

if t.Right != nil {
Walk(t.Right, ch)
}

ch <- t.Value
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch := make(chan int, 20)
go Walk(t1, ch)
go Walk(t2, ch)

res := 0
for i := 0; i < 20; i++ {
val := <-ch
res ^= val
}

return res == 0
}

func main() {
t1, t2 := tree.New(1), tree.New(1)
fmt.Printf("%v\n%v\n%v\n*****\n", t1, t2, Same(t1, t2))

t1, t2 = tree.New(2), tree.New(3)
fmt.Printf("%v\n%v\n%v\n*****\n", t1, t2, Same(t1, t2))
}```