github.com/spotify/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/misc/tour/solutions/binarytrees.go (about) 1 // Copyright 2012 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // +build ignore 6 7 package main 8 9 import ( 10 "fmt" 11 12 "code.google.com/p/go-tour/tree" 13 ) 14 15 func walkImpl(t *tree.Tree, ch chan int) { 16 if t.Left != nil { 17 walkImpl(t.Left, ch) 18 } 19 ch <- t.Value 20 if t.Right != nil { 21 walkImpl(t.Right, ch) 22 } 23 } 24 25 // Walk walks the tree t sending all values 26 // from the tree to the channel ch. 27 func Walk(t *tree.Tree, ch chan int) { 28 walkImpl(t, ch) 29 // Need to close the channel here 30 close(ch) 31 } 32 33 // Same determines whether the trees 34 // t1 and t2 contain the same values. 35 func Same(t1, t2 *tree.Tree) bool { 36 w1, w2 := make(chan int), make(chan int) 37 38 go Walk(t1, w1) 39 go Walk(t2, w2) 40 41 for { 42 v1, ok1 := <-w1 43 v2, ok2 := <-w2 44 if v1 != v2 || ok1 != ok2 { 45 return false 46 } 47 if !ok1 { 48 break 49 } 50 } 51 return true 52 } 53 54 func main() { 55 fmt.Print("tree.New(1) == tree.New(1): ") 56 if Same(tree.New(1), tree.New(1)) { 57 fmt.Println("PASSED") 58 } else { 59 fmt.Println("FAILED") 60 } 61 62 fmt.Print("tree.New(1) != tree.New(2): ") 63 if !Same(tree.New(1), tree.New(2)) { 64 fmt.Println("PASSED") 65 } else { 66 fmt.Println("FAILED") 67 } 68 }