A Tour of Go Exercise: 69 Equivalent Binary Trees
如其广告所言,Go用于写Equivalent Binary Trees确实简便优雅
1 package main 2 3 import "tour/tree" 4 import "fmt" 5 6 // Walk walks the tree t sending all values 7 // from the tree to the channel ch. 8 func Walk(t *tree.Tree, ch chan int){ 9 if t == nil { 10 return 11 } 12 Walk(t.Left, ch) 13 ch <- t.Value 14 Walk(t.Right, ch) 15 16 } 17 18 // Same determines whether the trees 19 // t1 and t2 contain the same values. 20 func Same(t1, t2 *tree.Tree) bool{ 21 cht1 := make (chan int, 10) 22 cht2 := make (chan int, 10) 23 go Walk(t1, cht1) 24 go Walk(t2, cht2) 25 for i := 0; i < 10; i++{ 26 if <-cht1 != <-cht2{ 27 return false 28 } 29 } 30 return true 31 } 32 33 func main() { 34 fmt.Println(Same(tree.New(1), tree.New(2))) 35 }