Created
December 25, 2013 07:00
-
-
Save kaipakartik/8120855 to your computer and use it in GitHub Desktop.
Exercise: Equivalent Binary Trees
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" | |
"fmt" | |
) | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
WalkRecursive(t, ch) | |
close(ch) | |
} | |
func WalkRecursive(t *tree.Tree, ch chan int) { | |
if t != nil { | |
WalkRecursive(t.Left, ch) | |
ch <- t.Value | |
WalkRecursive(t.Right, ch) | |
} | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
ch1, ch2 := make(chan int), make(chan int) | |
go Walk(t1, ch1) | |
go Walk(t2, ch2) | |
for { | |
n1, ok1 := <- ch1 | |
n2, ok2 := <- ch2 | |
if ok1 != ok2 || n1 != n2 { | |
return false | |
} | |
if !ok1 { | |
break; | |
} | |
} | |
return true | |
} | |
func main() { | |
ch := make(chan int) | |
go Walk(tree.New(1), ch) | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(2), tree.New(1))) | |
} |
The same function must check whether t1 and t2 have the same values in any order. The implementation returns instead, whether the order is of the elements the same in both parameters.
The requirement specifically states:
constructs a randomly-structured (but always sorted) binary tree
So, the solutions provided are all correct; they rely on the tree always being sorted. Not much use for a binary tree if it wouldn't be, anyhow
sorted and balanced are different things. The functions written above do not work.
For example, the tree.New(1) function can return the following trees:
They are both sorted, but the structure is different. The functions written above return false for these two trees, although they should be true
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe this does not work. It says both functions work, but that seems to be due to two mistakes cancelling each other out.
Basically, the
for
loop inSame()
usesi < cap(ch1)
as an ending condition, which will never loop once as it is alwaysfalse
, due tocap(ch)
always being0
for an unbuffered channelch
. Thus,Same()
always returnstrue
no matter the input. Correct me if I'm wrong, though!The reason it works is because in
testSame()
we test that both calls returntrue
, when we would actually expect the second one to returnfalse
.