Last active
January 15, 2018 02:27
-
-
Save brianjester/cfa14b7a78a00419fb20c8b3b57044cc to your computer and use it in GitHub Desktop.
Working with trees in golang
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 "fmt" | |
import "golang.org/x/tour/tree" | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
fmt.Println(t) | |
Climb(t, ch) | |
close(ch) | |
} | |
func Climb(t *tree.Tree, ch chan int) { | |
if t != nil { | |
Climb(t.Left, ch) | |
ch <- t.Value | |
Climb(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) | |
for { | |
x1, ok1 := <-ch1 | |
x2, ok2 := <-ch2 | |
switch { | |
case x1 != x2: //trees value differs | |
return false | |
case !ok1 && !ok2: //both are empty | |
return true | |
case ok1 != ok2: //trees size differs | |
return false | |
default: | |
//keep going | |
} | |
} | |
} | |
func main() { | |
ch := make(chan int) | |
go Walk(tree.New(1), ch) | |
//Prints out from channel below | |
for i := range ch { | |
fmt.Println(i) | |
} | |
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