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) { walkRecurse(t, ch) close(ch) } func walkRecurse(t *tree.Tree, ch chan int) { if t.Left != nil { walkRecurse(t.Left, ch) } ch <- t.Value if t.Right != nil { walkRecurse(t.Right, ch) } } // Same determines whether the trees // t1 and t2 contain the same values. func Same(t1, t2 *tree.Tree) bool { t1Ch := make(chan int) t2Ch := make(chan int) go Walk(t1, t1Ch) go Walk(t2, t2Ch) t1Values := map[int]struct{}{} for v1 := range t1Ch { if _, seen := t1Values[v1]; !seen { t1Values[v1] = struct{}{} } } for v2 := range t2Ch { if _, seen := t1Values[v2]; !seen { return false } } return true } func main() { t := tree.New(1) values := make(chan int) go Walk(t, values) for v := range values { fmt.Println(v) } t1, t2 := tree.New(1), tree.New(2) fmt.Println(Same(t1, t2)) }