Skip to content

Instantly share code, notes, and snippets.

@kmarenov
Created September 5, 2021 12:16
Show Gist options
  • Select an option

  • Save kmarenov/0276950deb6886a5e5c402d45aefec3e to your computer and use it in GitHub Desktop.

Select an option

Save kmarenov/0276950deb6886a5e5c402d45aefec3e to your computer and use it in GitHub Desktop.
Exercise: Equivalent Binary Trees
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)};
ch <- t.Value;
if t.Right != nil {Walk(t.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)
go Walk(t1, c1)
c2 := make(chan int)
go Walk(t2, c2)
for i := 0; i < 10; i++ {
if <-c1 != <-c2 {
return false;
}
}
return true;
}
func main() {
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