Last active
March 10, 2021 12:32
-
-
Save m99coder/c82ee5118dd00ec485ea7dd9199194bc to your computer and use it in GitHub Desktop.
Concurrency and channels to walk binary trees
This file contains hidden or 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 ( | |
"fmt" | |
"golang.org/x/tour/tree" | |
) | |
func Walk(t *tree.Tree, ch chan int) { | |
defer close(ch) | |
// using a closure | |
var walk func(t *tree.Tree) | |
walk = func(t *tree.Tree) { | |
if t == nil { | |
return | |
} | |
walk(t.Left) | |
ch <- t.Value | |
walk(t.Right) | |
} | |
walk(t) | |
} | |
func Same(t1, t2 *tree.Tree) bool { | |
ch1, ch2 := make(chan int), make(chan int) | |
go Walk(t1, ch1) | |
go Walk(t2, ch2) | |
for { | |
n1, ok1 := <- ch1 | |
n2, ok2 := <- ch2 | |
if ok1 != ok2 || n1 != n2 { | |
return false | |
} | |
if !ok1 { | |
break | |
} | |
} | |
return true | |
} | |
func main() { | |
ch := make(chan int) | |
go Walk(tree.New(1), ch) | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(2), tree.New(1))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment