Go Tour Exercise: Equivalent Binary Trees

前端 未结 23 1794
攒了一身酷
攒了一身酷 2020-12-12 23:39

I am trying to solve equivalent binary trees exercise on go tour. Here is what I did;

package main

import \"tour/tree\"
import \"fmt\"

// Walk walks the tr         


        
23条回答
  •  春和景丽
    2020-12-13 00:31

    While my first intuition was to also wrap the recursive walk and closing the channels, I felt it was not in the spirit of the exercise.

    The exercise text contains the following information:

    The function tree.New(k) constructs a randomly-structured (but always sorted) binary tree holding the values k, 2k, 3k, ..., 10k.

    Which clearly states that the resulting trees have exactly 10 nodes.

    Therefore, in the spirit and simplicity of this exercise, I went with the following solution:

    package main
    
    import (
        "fmt"
        "golang.org/x/tour/tree"
    )
    
    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)
        }
    }
    
    func Same(t1, t2 *tree.Tree) bool {
        ch1 := make(chan int)
        ch2 := make(chan int)
    
        defer close(ch1)
        defer close(ch2)
    
        go Walk(t1, ch1)
        go Walk(t2, ch2)
    
        for i := 0; i < 10; i++ {
            if <-ch1 != <-ch2 {
                return false
            }
        }
    
        return true
    }
    
    func main() {
        fmt.Println(Same(tree.New(1), tree.New(2)))
    }
    

    If the goal would be to run on arbitrarily sized trees, then reacting to closed channels is the better solution, but I felt this was a simple exercise with intentionally put constraints to make it easier for the new Gopher.

提交回复
热议问题