github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2014/go4gophers/tree-thread.go (about)

     1  // +build OMIT
     2  
     3  package main
     4  
     5  import (
     6  	"fmt"
     7  
     8  	"code.google.com/p/go-tour/tree"
     9  )
    10  
    11  func Walk(root *tree.Tree) chan int {
    12  	ch := make(chan int)
    13  	go func() {
    14  		walk(root, ch)
    15  		close(ch)
    16  	}()
    17  	return ch
    18  }
    19  
    20  func walk(t *tree.Tree, ch chan int) {
    21  	if t.Left != nil {
    22  		walk(t.Left, ch)
    23  	}
    24  	ch <- t.Value
    25  	if t.Right != nil {
    26  		walk(t.Right, ch)
    27  	}
    28  }
    29  
    30  // STOP OMIT
    31  
    32  func Same(t1, t2 *tree.Tree) bool {
    33  	w1, w2 := Walk(t1), Walk(t2)
    34  	for {
    35  		v1, ok1 := <-w1
    36  		v2, ok2 := <-w2
    37  		if v1 != v2 || ok1 != ok2 {
    38  			return false
    39  		}
    40  		if !ok1 {
    41  			return true
    42  		}
    43  	}
    44  }
    45  
    46  func main() {
    47  	fmt.Println(Same(tree.New(3), tree.New(3)))
    48  	fmt.Println(Same(tree.New(1), tree.New(2)))
    49  }