Is it possible to use recursion in an iterator implementing System.Collections.IEnumerable
? I have a tree structure declared roughly like this:
public class Node
{
public Node Sibling;
public Node Child;
}
I would like to iterate over the nodes in a tree. I would like to do something like this (pseudocode, I guess this won't compile):
public class NodeIterator : System.Collections.IEnumerable
{
Node m_root;
public System.Collections.IEnumerator GetEnumerator()
{
recursiveYield(m_root);
}
System.Collections.IEnumeraton recursiveYield(Node node)
{
yield return node;
if (node.Child)
{
recursiveYield(node.Child);
}
if (node.Sibling)
{
recursiveYield(node.Sibling);
}
}
}
Is this somehow possible? I realise this can be solved without recursion using a Node
deque in the GetEnumerator
function.