Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Voronoff
Created December 7, 2012 23:40
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 Voronoff/4237565 to your computer and use it in GitHub Desktop.
Save Voronoff/4237565 to your computer and use it in GitHub Desktop.
Generalized solution for comparing binary trees of integers
//Solution for tour.golang.org/#70
//Generalized so it neither requires trees of the same size
//nor sorted trees - where the value of the node to left is smaller
//than the current node and the value to the right is greater
//by David Allen
package main
import (
"tour/tree"
"fmt"
)
func Walk(t *tree.Tree, ch chan int){
var _walk func(*tree.Tree)
_walk = func(t *tree.Tree){
if (t != nil){
_walk(t.Left)
ch <- t.Value
_walk(t.Right)
}
}
_walk(t)
close(ch)
}
func Same(t1, t2 *tree.Tree) bool{
mapped_tree1, mapped_tree2 := MapTree(t1), MapTree(t2)
for i, v := range mapped_tree1{
if (mapped_tree2[i] != v) {
return false
} else {
delete(mapped_tree2,i)
}
}
if (len(mapped_tree2) != 0){
return false
}
return true
}
func MapTree(t *tree.Tree) map[int]int {
c := make(chan int)
mapped_tree := make(map[int]int)
go Walk(t, c)
for i := range c{
mapped_tree[i] += 1
}
return mapped_tree
}
func main() {
fmt.Println(Same(tree.New(3), tree.New(3)))
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