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.
Yes, all you need is to iterate the return value from the call site. Like so:
IEnumerable<T> Recursive(Node node)
{
yield return node;
foreach (var siblingNode in Recursive(node.Sibling))
{
yield return siblingNode;
}
foreach (var childNode in Recursive(node.Child))
{
yield return childNode;
}
}
For the record, this isn't better than using a queue to achieve e.g. breadth-first traversal. The memory requirement for something like this is identical in the worst case.
No because the recursiveYield(Node node)
function would return a collection and you can only yield an item
精彩评论