LoginSignup
0
0

More than 5 years have passed since last update.

The answer to "Exercise: Equivalent Binary Trees" in A Tour of Go

Last updated at Posted at 2018-11-21

package main

import (
        "fmt"
        "reflect"
        "sort"

        "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) {
        if t == nil {
                return
        } else {
                ch <- t.Value
        }
        Walk(t.Left, ch)
        Walk(t.Right, ch)
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
        n := 10
        a1 := make([]int, n)
        a2 := make([]int, n)

        ch1 := make(chan int, 1)
        go Walk(t1, ch1)
        for i := 0; i < n; i++ {
                a1[i] = <-ch1
        }
        close(ch1)
        ch2 := make(chan int, 1)
        go Walk(t2, ch2)
        for i := 0; i < n; i++ {
                a2[i] = <-ch2
        }
        close(ch2)

        sort.Ints(a1)
        sort.Ints(a2)
        fmt.Println(a1, a2)
        return reflect.DeepEqual(a1, a2)
}

func main() {
        //fmt.Println("%v,%T", argn, argn)
        ch := make(chan int, 1)
        //x, _ := strconv.Atoi(argn)
        x := 1
        go Walk(tree.New(x), 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)))
}
10
5
3
1
2
4
7
6
9
8
[1 2 3 4 5 6 7 8 9 10] [1 2 3 4 5 6 7 8 9 10]
true
[1 2 3 4 5 6 7 8 9 10] [2 4 6 8 10 12 14 16 18 20]
false

Refs.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0