Answer the question
In order to leave comments, you need to log in
How does recursion work when iterating?
I implement a simple traversal of the binary tree by recursion, why does not the recursive call traverse(current.left) occur during iteration? and traverse(current.right); ? It just returns a single value yield return current.value;
IEnumerator traverse(Node current) {
if (current != null)
{
traverse(current.left);
yield return current.value;
traverse(current.right);
}
}
public IEnumerator GetEnumerator()
{
return traverse(core);
}
Answer the question
In order to leave comments, you need to log in
IEnumerable<T> traverse(Node current) {
if (current != null)
{
foreach (var value in traverse(current.left))
yield return value;
yield return current.value;
foreach (var value in traverse(current.right))
yield return value;
}
}
yield return just remembers the current position of the iterator. Therefore, yield return current.value will return the same value, the first one, because You are not iterating over the traverse(node) collection, there are no methods that will do MoveNext(). Look at Mikhail Makarov 's variant , where iteration occurs using foreach.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question