Created
May 10, 2021 05:43
-
-
Save magicoder10/0d1309a05bcfdac3b6a6c94bd6069b96 to your computer and use it in GitHub Desktop.
Equivalent Binary Tree
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" | |
) | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
WalkRec(t, ch) | |
close(ch) | |
} | |
func WalkRec(t *tree.Tree, ch chan int) { | |
if t == nil { | |
return | |
} | |
WalkRec(t.Left, ch) | |
ch <- t.Value | |
WalkRec(t.Right, ch) | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
t1Vals, t2Vals := make(chan int), make(chan int) | |
go Walk(t1, t1Vals) | |
go Walk(t2, t2Vals) | |
for { | |
t1Val, t1Ok := <- t1Vals | |
t2Val, t2Ok := <- t2Vals | |
if t1Ok != t2Ok { | |
return false | |
} | |
if t2Val != t1Val { | |
return false | |
} | |
if !t1Ok { | |
break; | |
} | |
} | |
return true | |
} | |
func main() { | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
fmt.Println(Same(nil, tree.New(1))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment