T
T
th0m4sXD2017-12-18 00:38:11
recursion
th0m4sXD, 2017-12-18 00:38:11

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

2 answer(s)
M
Mikhail Makarov, 2017-12-18
@th0m4sXD

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;
    }
}

E
eRKa, 2017-12-18
@kttotto

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 question

Ask a Question

731 491 924 answers to any question