Created
December 7, 2012 23:40
-
-
Save Voronoff/4237565 to your computer and use it in GitHub Desktop.
Generalized solution for comparing binary trees of integers
This file contains hidden or 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
//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