exercise: complete the exercise Equivalent Binary Trees with goroutine and channel

master
oscarzhou 2021-04-28 23:22:35 +12:00
parent 684b0a09b8
commit 2a77e80aec
2 changed files with 143 additions and 0 deletions

View File

@ -0,0 +1,68 @@
## Test cases
### Test Case 1
```
fmt.Println(Same(tree.New(1), tree.New(1)))
```
**output**
```
```
### Test Case 2
```
t := tree.New(1)
fmt.Println(Same(t, t))
```
**output**
```
ch2
10
ch1
10
ch2
5
ch1
5
ch2
3
ch1
3
ch2
2
ch1
2
ch2
7
ch1
7
ch2
9
ch1
9
ch2
8
ch1
8
ch2 done
0
true
```
### Test Case 3
```
fmt.Println(Same(tree.New(1), tree.New(2)))
```
**output**

View File

@ -0,0 +1,75 @@
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
func Walk(t *tree.Tree, ch chan int) {
walk(t, ch)
close(ch)
}
// walk traverses the tree by the pre-order
func walk(t *tree.Tree, ch chan int) {
if t != nil {
ch <- t.Value
walk(t.Left, ch)
walk(t.Right, ch)
}
}
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
x, y := 0, 0
ok := true
for {
select {
case x, ok = <-ch1:
if !ok {
return true
}
y = <-ch2
if x != y {
return false
}
case x, ok = <-ch2:
if !ok {
fmt.Println("ch2 done")
fmt.Println(x)
return true
}
fmt.Println("ch2")
fmt.Println(x)
y = <-ch1
fmt.Println("ch1")
fmt.Println(y)
if x != y {
return false
}
}
}
return true
}
func main() {
// fmt.Println(Same(tree.New(1), tree.New(1)))
t := tree.New(1)
fmt.Println(Same(t, t))
// fmt.Println(Same(tree.New(1), tree.New(2)))
}