Created
July 10, 2016 16:34
-
-
Save galch/b59483855f03ac5fbd15666d9bc02a5b to your computer and use it in GitHub Desktop.
A Tour of Go - [Exercise: Equivalent Binary Trees](https://tour.golang.org/concurrency/7) & [연습: 동등한 이진 트리](https://go-tour-kr.appspot.com/#70)
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 "code.google.com/p/go-tour/tree" | |
import "fmt" | |
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 == nil { | |
return | |
} | |
// Inorder Traversal | |
Walk(t.Left, ch) | |
ch <- t.Value | |
Walk(t.Right, ch) | |
} | |
func Walker(t *tree.Tree, ch chan int) { | |
Walk(t, ch) | |
close(ch) | |
} | |
// 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 Walker(t1, ch1) | |
go Walker(t2, ch2) | |
for x := range ch1 { | |
if v := <-ch2; x != v { | |
return false | |
} | |
} | |
return true | |
} | |
func main() { | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(2), tree.New(1))) | |
fmt.Println(Same(tree.New(2), tree.New(2))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment