mirror of
https://github.com/blindlobstar/go-interview-problems
synced 2025-04-30 21:55:13 +00:00
46 lines
725 B
Go
46 lines
725 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"golang.org/x/tour/tree"
|
|
)
|
|
|
|
// Walk walks the tree t sending all values
|
|
// from the tree to the channel ch.
|
|
func Walk(t *tree.Tree, ch chan int) {
|
|
defer close(ch)
|
|
goWalk(t, ch)
|
|
}
|
|
|
|
func goWalk(t *tree.Tree, ch chan int) {
|
|
if t == nil {
|
|
return
|
|
}
|
|
goWalk(t.Left, ch)
|
|
ch <- t.Value
|
|
goWalk(t.Right, ch)
|
|
}
|
|
|
|
// Same determines whether the trees
|
|
// t1 and t2 contain the same values.
|
|
func Same(t1, t2 *tree.Tree) bool {
|
|
ch1, ch2 := make(chan int), make(chan int)
|
|
go Walk(t1, ch1)
|
|
go Walk(t2, ch2)
|
|
for {
|
|
v1, ok1 := <-ch1
|
|
v2, ok2 := <-ch2
|
|
if ok1 != ok2 || v1 != v2 {
|
|
return false
|
|
}
|
|
if !ok1 {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
fmt.Println(Same(tree.New(1), tree.New(2)))
|
|
}
|