简体   繁体   English

C#迭代器中的递归

[英]Recursion in C# iterator

Is it possible to use recursion in an iterator implementing System.Collections.IEnumerable ? 是否可以在实现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. 我意识到这可以使用GetEnumerator函数中的Node deque在没有递归的情况下解决。

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 eg breadth-first traversal. 对于记录,这并不比使用队列实现例如广度优先遍历更好。 The memory requirement for something like this is identical in the worst case. 在最坏的情况下,类似这样的内存需求是相同的。

不,因为recursiveYield(Node node)函数将返回一个集合,您只能生成一个项目

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM