-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathequivalent_binary_trees.go
More file actions
59 lines (46 loc) · 873 Bytes
/
Copy pathequivalent_binary_trees.go
File metadata and controls
59 lines (46 loc) · 873 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
type Tree struct {
Left *Tree
Value int
Right *Tree
}
// Walk walks the tree t sending all values
// from the tree to the channel 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)
}
return
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1, ch2 := make(chan int), make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := 0; i < 10; i++ {
cur1 := <-ch1
cur2 := <-ch2
if cur1 != cur2 {
return false
}
}
return true
}
func main() {
ch := make(chan int, 1)
go Walk(tree.New(1), ch)
for i := 0; i < 10; i++ {
fmt.Println(<-ch)
}
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(1), tree.New(2)))
}