Skip to content

Instantly share code, notes, and snippets.

@flc
Created September 5, 2013 16:07
Show Gist options
  • Save flc/6452260 to your computer and use it in GitHub Desktop.
Save flc/6452260 to your computer and use it in GitHub Desktop.
A Tour of Go - Exercise: Equivalent Binary Trees http://tour.golang.org/#70
package main
import "code.google.com/p/go-tour/tree"
import "fmt"
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)
}
}
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
_walk(t, ch)
close(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)
for {
val1, ok1 := <- c1
val2, ok2 := <- c2
if !ok1 || !ok2 { // one of them finished
if ok1 != ok2 { // they didn't finished at the same time
return false
}
break
}
if val1 != val2 {
return false
}
}
return true
}
func main() {
k := 1
ch := make(chan int)
tr := tree.New(k)
go Walk(tr, ch)
for i:=0; i < 10; i++ {
fmt.Println(<-ch)
}
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}
@yshdzw
Copy link

yshdzw commented Sep 20, 2021

package main

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

func Walk(t *tree.Tree, ch chan int) {
	if t == nil {
		return
	}
	
	Walk(t.Left, ch)
	ch <- t.Value
	Walk(t.Right, ch)
}

func Same(t1, t2 *tree.Tree) bool {
	// Way 2 :
	//return fmt.Sprintf("%v", *t1) == fmt.Sprintf("%v", *t2)
	
	// Way 1 -- START
	ch1 := make(chan int)
	ch2 := make(chan int)
	
	go Walk(t1, ch1)
	go Walk(t2, ch2)
	
	if <-ch1 != <-ch2 {
		close(ch1)
		close(ch2)
		return false
	}
	return true
	// Way 1 -- END
}

func main() {
	//fmt.Println(Same(tree.New(1), tree.New(1))) // true
	
	t1 := tree.New(1)
	t2 := tree.New(2)
	fmt.Println(t1, "\n", t2)
	fmt.Println(Same(t1, t2)) // false
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment