Created
December 25, 2017 11:56
-
-
Save harryhare/7057342d3018eaa955f819c190023b4d to your computer and use it in GitHub Desktop.
Exercise: Equivalent Binary Trees https://tour.golang.org/concurrency/8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"golang.org/x/tour/tree" | |
"fmt" | |
) | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int){ | |
walk(t,ch) | |
//close(ch) | |
} | |
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) | |
} | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool{ | |
c1 := make(chan int,10) | |
go Walk(t1,c1) | |
c2 := make(chan int,10) | |
go Walk(t2,c2) | |
for i:=0;i<10;i++{ | |
a,oka := <- c1 | |
b,okb := <- c2 | |
if oka!=okb ||a!=b { | |
return false | |
} | |
} | |
return true | |
} | |
func test1(){ | |
t1 := tree.New(1) | |
t2 := tree.New(1) | |
c1 := make(chan int) | |
c2 := make(chan int) | |
go Walk(t1,c1) | |
go Walk(t2,c2) | |
//fmt.Printf("%v",Same(t1,t2)) | |
for i:=0; i<10;i++{ | |
fmt.Printf("%d",<-c1) | |
fmt.Printf(" %d\n",<-c2) | |
} | |
} | |
func test2(){ | |
t1 := tree.New(1) | |
t2 := tree.New(1) | |
c1 := make(chan int,10) | |
c2 := make(chan int,10) | |
go Walk(t1,c1) | |
go Walk(t2,c2) | |
fmt.Printf("%v",Same(t1,t2)) | |
} | |
func test0(){ | |
t := tree.New(1) | |
c := make(chan int) | |
go Walk(t,c) | |
for i := 0; i < 10; i++{ | |
fmt.Println(<-c) | |
} | |
} | |
func main() { | |
test2(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment