Created
January 10, 2022 04:20
-
-
Save thaihuynhxyz/0a1bf194084fa1dfccdad5e716cf4cf6 to your computer and use it in GitHub Desktop.
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) { | |
defer close(ch) // <- closes the channel when this function returns | |
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) | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
ch1 := make(chan int) | |
ch2 := make(chan int) | |
go Walk(t1, ch1) | |
go Walk(t2, ch2) | |
for i1 := range ch1 { | |
if i2, ok := <-ch2; !ok || i1 != i2 { | |
return false | |
} | |
} | |
if _, ok := <-ch2; ok { | |
return false | |
} | |
return true | |
} | |
func main() { | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment