Go Tour Exercise #7: Equivalence of Binary Trees
When attempting the binary trees equivalence exercise in the Go tour, you may encounter a challenge in signaling when there are no more elements left in the trees. The given code attempts to use a channel to communicate values from the trees, but it fails to address this signaling issue.
The Problem
Closing a channel during recursive traversal prematurely terminates the transmission of values. Using close(ch) within the Walk() function closes the channel before all values are sent.
A Solution Using Closure
A closure allows you to create an anonymous function that captures variables from the surrounding scope. This can be used to generate a custom walk function that automatically closes the channel when its execution is complete.
func Walk(t *tree.Tree, ch chan int) { defer close(ch) // Automatically closes the channel when this function returns var walk func(t *tree.Tree) walk = func(t *tree.Tree) { if t == nil { return } walk(t.Left) ch <- t.Value walk(t.Right) } walk(t) }
In this solution, the Walk() function returns a walk closure that handles the traversal of the tree. When the closure exits, it automatically closes the channel, indicating that there are no more values to be sent. This ensures that the receiving end can determine when the traversal is complete.
The above is the detailed content of How Can I Properly Signal the End of Traversal in a Go Binary Tree Equivalence Exercise?. For more information, please follow other related articles on the PHP Chinese website!