Created
June 12, 2018 13:33
-
-
Save kamynina/a08d140a0eb526c3cc53f638a3249c09 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 ( | |
"fmt" | |
"golang.org/x/tour/tree" | |
"sort" | |
) | |
func Walk(t *tree.Tree, ch chan int) { | |
WalkSub(t, ch) | |
close(ch) | |
} | |
func WalkSub(t *tree.Tree, ch chan int) { | |
ch <- t.Value | |
left, right := t.Left, t.Right | |
if left != nil { | |
WalkSub(left, ch) | |
} | |
if right != nil { | |
WalkSub(right, ch) | |
} | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
c1 := make(chan int) | |
c2 := make(chan int) | |
go Walk(t1, c1) | |
go Walk(t2, c2) | |
ar1 := flatTree(t1, c1) | |
ar2 := flatTree(t2, c2) | |
for i, x := range ar1 { | |
if ar2[i] != x { | |
return false | |
} | |
} | |
return true | |
} | |
func flatTree(t *tree.Tree, c chan int) []int { | |
a := []int{} | |
for x := range c { | |
a = append(a, x) | |
} | |
sort.Ints(a) | |
return a | |
} | |
func main() { | |
t1 := tree.New(2) | |
t2 := tree.New(2) | |
fmt.Println(Same(t1, t2)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment