The A Tour of Go “Equivalent Binary Trees” exercise asks you to write a Walk function that sends a tree’s values into a channel in ascending order and a Same function that reports whether two trees hold the same sequence of values; the intended solution is to compare the two in-order traversals element by element, which works because a binary search tree’s in-order walk visits its keys in sorted order. The exercise’s concrete signature is func Walk(t *tree.Tree, ch chan int) and func Same(t1, t2 *tree.Tree) bool, using the golang.org/x/tour/tree package, whose tree.Tree has exported fields Left, Right, and Value. Two subtleties trip people up: Same must not be implemented by building two full slices unless you also close the channels correctly, and the tree type is a binary search tree, so “equivalent” here means “same multiset of values in sorted order,” not “identical shape.”
What the exercise actually gives you
The Tour provides a package, golang.org/x/tour/tree, with a type roughly like this:
and a constructor tree.New(k), which returns a randomly shaped binary search tree containing the values k, 2k, 3k, …, 10k. Because the shape is random but the value set is fixed, tree.New(1) and tree.New(1) will almost always have different shapes but the same values. That is the entire point: the exercise wants you to test equivalence of contents, not structure.
The exercise also supplies a stub file (exercise-equivalent-binary-trees.go) with:
Your job is to fill in Walk and Same, then write a main that demonstrates the result. The grader (and the Tour’s own “run” button) only checks that the program compiles and runs; it does not verify correctness automatically, so you must reason about it yourself.
Why in-order traversal is the key idea
A binary search tree maintains the invariant that for every node, all values in its left subtree are smaller and all values in its right subtree are larger. An in-order traversal—recurse left, visit the node, recurse right—therefore emits values in nondecreasing order. That is a defining property, not an accident.
So if two binary search trees contain the same multiset of values, their in-order traversals produce identical sequences. Conversely, if their in-order traversals differ, the value sets differ. That equivalence is what makes the exercise solvable without sorting, hashing, or comparing shapes.
This is also where the exercise’s naming is slightly loose. “Equivalent” in the Tour means same values, and it relies on the input being a valid BST. If you fed Walk a tree that violated the BST invariant, the output would no longer be sorted and the equivalence test would be unreliable. The exercise never asks you to handle that case; it assumes the tree package’s contract.
A correct Walk
The cleanest version uses a helper for the recursion so the top-level call does not close the channel prematurely:
Two design decisions matter here.
First, the closure inside Walk rather than inside the recursive helper. If you closed the channel inside walk, you would close it on the first leaf you finish and panic on the next send. Closing belongs at the top level, after the entire traversal completes.
Second, whether to close at all. The exercise’s stub does not tell you to close, and Same can be written without closure. But closing is idiomatic Go for a producer that finishes, and it enables for v := range ch on the consumer side. The Tour’s own discussion does not mandate it, so treat closure as a good practice rather than a hard requirement of the exercise.
If you prefer an explicit stack instead of recursion, that is also valid and avoids any concern about deep trees overflowing the goroutine stack (Go grows stacks dynamically, so this is rarely an issue in practice):
Both versions produce the same ascending sequence. The recursive one is shorter and clearer for a Tour exercise; the iterative one is a reasonable answer if you are asked to avoid recursion in an interview.
A correct Same
The straightforward implementation walks both trees concurrently and compares values as they arrive:
The final return ok1 == ok2 handles the case where one tree is exhausted before the other: if both channels close at the same step, the trees are equivalent; if exactly one closes first, one tree has more values, so they differ. That single line is the most commonly missed piece. Beginners often write if !ok1 || !ok2 { return false }, which incorrectly reports two equal trees as unequal (both channels close together and the function returns false).
An alternative is to drain both channels into slices and compare with reflect.DeepEqual or a manual loop:
This version is easier to read and to debug, at the cost of buffering all values and losing the streaming property. For a Tour exercise either is acceptable; the concurrent version is more in the spirit of Go’s channel idioms, and it terminates as soon as it finds a mismatch.
A main that actually exercises the code
The Tour’s stub leaves main empty. A minimal demonstrative version:
tree.New(1) and tree.New(1) produce the values 1 through 10 in some random shape, so Same should print true. tree.New(2) produces 2, 4, …, 20, so Same should print false. The Walk demonstration prints 1 through 10 in order, which visually confirms the sorting property.
One caveat: because tree.New is randomized, Same(tree.New(1), tree.New(1)) returning true on a single run does not prove your implementation is correct in general. It is a sanity check, not a test suite. To gain confidence, run it several times, and also test degenerate cases: an empty tree, a single-node tree, and a tree with duplicate values (the Tour package does not produce duplicates, but you could construct one manually).
Common failure patterns and how to recognize them
Closing the channel too early. If you close inside the recursive helper, you get panic: send on closed channel. The fix is to move close(ch) to the non-recursive wrapper, as shown above. If you do not close at all, for v := range ch blocks forever.
Assuming sorted order without a BST. If you rewrite Walk to do a pre-order or post-order traversal, the output is not sorted, and Same will reject trees that are actually equivalent. The exercise’s correctness depends on in-order traversal and on the BST invariant. This is worth stating explicitly because it is the conceptual heart of the exercise, not a mere implementation detail.
Comparing structures instead of values. A tempting shortcut is to compare t1.Left == t2.Left recursively. That fails immediately when the trees have different shapes but the same values, which is the normal case for tree.New(k) called twice. The exercise exists to push you toward the channel-based value comparison.
Deadlock from unbuffered channels. If you call Walk synchronously (without go) and then try to read from the channel in the same goroutine, the first send blocks forever. Either launch Walk in a goroutine or give the channel enough buffer (a buffer of 10 would work for tree.New(k), but not for arbitrary trees). The goroutine approach is the general one.
Off-by-one in the exhaustion check. As noted above, return ok1 == ok2 is the correct condition. Writing return !ok1 && !ok2 achieves the same thing here because you return only when at least one is closed, but the equality form is clearer. Writing return false when either closes is the classic bug.
What “equivalent” does not mean
The Tour exercise uses “equivalent” in a narrow sense: same multiset of values, compared via sorted order. It does not mean:
Isomorphic trees. Two trees with the same values but different shapes are equivalent by the exercise’s definition. That is deliberate; the randomized tree.New makes shape-matching impossible. Same pointer identity. Same(t, t) should be true, but the exercise never asks you to check identity, and a correct implementation will return true for distinct but value-equal trees as well. Same type or metadata. The tree.Tree type carries no metadata beyond Value. If you generalize the exercise to a tree type with, say, color or priority fields, “equivalent” would need redefinition. Sorted without duplicates. The exercise’s package does not generate duplicates, but nothing in the algorithm forbids them. If duplicates were present, in-order traversal would emit them adjacently, and Same would still work correctly.
The distinction between structural equivalence and value equivalence is a recurring theme in computer science—it shows up in comparing JSON documents, ASTs, and database rows. The Tour exercise is a small, clean introduction to that idea using channels.
Channel mechanics worth understanding
The exercise is as much about Go concurrency as about trees. A few points that repay attention:
Unbuffered channels synchronize. When Walk sends a value, it blocks until a receiver takes it. This means the producer and consumer proceed in lockstep, which is fine for Same because both walks advance at the same rate. It also means a bug in one side (e.g., not reading) hangs the whole program rather than producing a wrong answer—a common source of confusion when debugging.
Closing is a signal, not a value. Receiving from a closed channel yields the zero value and ok == false. This is why for v := range ch terminates cleanly. If you never close, the consumer has no way to know the producer is done, and you must rely on an external count or a separate done channel.
Goroutine leaks. If Same returns false early (on a value mismatch), one or both Walk goroutines may still be blocked trying to send. In this short program that is harmless because the process exits, but in a long-running server it would leak goroutines. A more robust version would use a done channel or context.Context to cancel the walkers. The Tour exercise does not require this, but it is the kind of thing a reviewer will ask about if you present the solution in an interview.
A cancellation-aware variant:
This is beyond the exercise’s scope but shows the direction a production-quality version would take.
How this connects to the surrounding Tour lessons
The Equivalent Binary Trees exercise sits in the “Concurrency” section, after goroutines, channels, buffered channels, range and close, and select. It is deliberately placed there because the natural solution uses all of those features: goroutines to run the two walks concurrently, channels to carry values, range/close to consume until exhaustion, and (optionally) select for cancellation. The tree traversal itself is elementary; the pedagogical payload is the concurrency pattern of two producers feeding a comparator.
It also follows the “Binary Trees” exercise, which asks you to implement Walk alone. If you did that one first, the only new work here is Same. If you skipped it, the combined exercise is still self-contained. The Tour does not link the two exercises formally, but they share the same package and the same traversal idea.
Testing beyond the Tour
Because the Tour’s environment does not run tests, you may want to copy the exercise into a local Go module and write a _test.go file. A useful set:
Same(tree.New(1), tree.New(1)) is true across many runs. Same(tree.New(1), tree.New(2)) is false. Same(nil, nil) is true (both walks close immediately). Same(tree.New(1), nil) is false. A hand-built tree with duplicate values matches another with the same duplicates. A hand-built non-BST (e.g., root 5 with left child 10) is not required to behave sensibly; document that the function assumes BST input if you test it at all.
The nil cases are worth calling out because the recursive walk handles nil by returning immediately, and the top-level Walk then closes the channel, so Same(nil, nil) correctly returns true with the ok1 == ok2 logic.
A note on the query’s category
The request is filed under strength training and bodyweight exercise, which does not match the content: this is a Go programming exercise from the Tour of Go. The category appears to be a misclassification in the source metadata. The answer above addresses the programming question as asked; no fitness guidance is implied or relevant.
Frequently asked questions
Do I have to use goroutines in Same? No. The slice-collection version is correct without them. The goroutine version is more idiomatic for the Tour’s concurrency section and terminates earlier on mismatches.
Should Walk close the channel? The exercise stub does not say so, but closing is idiomatic and enables range. If you close, do it in the wrapper, not the recursive helper. If you do not close, Same must use explicit counts or a separate signal.
Why does my Same return false for two identical trees? The most likely cause is the exhaustion check: returning false as soon as either channel closes. Use return ok1 == ok2 so that simultaneous closure counts as equality.
Can I compare the trees without channels? Yes—an in-order traversal appending to slices, then comparing the slices, is equivalent in result. The channel version is what the exercise is steering you toward because of its placement in the concurrency chapter.
What if the tree has duplicate values? The algorithm still works: duplicates appear adjacently in both traversals, and the element-wise comparison handles them. The Tour’s tree.New does not generate duplicates, but nothing in the solution depends on uniqueness.
Is the tree guaranteed to be a BST? The tree.New constructor produces a BST. The exercise assumes BST input; if you pass a non-BST, in-order traversal is not sorted and the equivalence test is not meaningful. That assumption is implicit, not stated in the stub, which is a common source of confusion for readers who try to generalize the function.
How large can the tree be before recursion is a problem? Go grows goroutine stacks dynamically, so recursion depth in the thousands is generally fine. For extremely deep or adversarial trees, the iterative stack version avoids any concern. The Tour’s trees have only 10 nodes, so this is theoretical for the exercise.
The exercise is small, but it rewards attention to three separate things: the BST invariant that makes in-order traversal sorted, the channel lifecycle (especially closing and the exhaustion check), and the distinction between value equivalence and structural equivalence. Getting all three right is what separates a solution that happens to print true once from one that is actually correct.