Created
August 17, 2020 11:39
-
-
Save supercede/11b604df6d4735660ff8edf40fd0fadd to your computer and use it in GitHub Desktop.
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
| // Go tour equivalent binary tree solution | |
| package main | |
| import ( | |
| "fmt" | |
| "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) { | |
| if t != nil { | |
| Walk(t.Left, ch) | |
| ch <- t.Value | |
| Walk(t.Right, ch) | |
| } | |
| } | |
| func goWalk(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 { | |
| c1 := make(chan int) | |
| c2 := make(chan int) | |
| go goWalk(t1, c1) | |
| go goWalk(t2, c2) | |
| for { | |
| v1, ok1 := <-c1 | |
| v2, ok2 := <-c2 | |
| fmt.Println(v1) | |
| if v1 != v2 || ok1 != ok2 { | |
| return false | |
| } | |
| if ok1 == false || ok2 == false { | |
| return true | |
| } | |
| } | |
| return true | |
| } | |
| func main() { | |
| myTree := tree.New(10) | |
| myOtherTree := tree.New(10) | |
| fmt.Println(Same(myTree, myOtherTree)) | |
| } |
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
| // Go Tour equivalent binary tree solution using lists | |
| package main | |
| import ( | |
| "fmt" | |
| "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, l *[]int) { | |
| if t != nil { | |
| Walk(t.Left, l) | |
| *l = append(*l, t.Value) | |
| Walk(t.Right, l) | |
| } | |
| } | |
| // Same determines whether the trees | |
| // t1 and t2 contain the same values. | |
| func Same(t1, t2 *tree.Tree) bool { | |
| var l1 []int | |
| var l2 []int | |
| Walk(t1, &l1) | |
| Walk(t2, &l2) | |
| if len(l1) != len(l2) { | |
| return false | |
| } | |
| for i, _ := range l1 { | |
| if l1[i] != l2[i] { | |
| return false | |
| } | |
| } | |
| return true | |
| } | |
| func main() { | |
| myTree := tree.New(10) | |
| myOtherTree := tree.New(9) | |
| fmt.Println(Same(myTree, myOtherTree)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment