递归和计算器

Recursion and stackoverflow

我 class 喜欢

 public class Question
    {
        private readonly int questionID;
                private List<Question> similarquestions; // Similarity is bidirectional
}

为了得到所有嵌套的 classes 我使用像

这样的递归方法
public static IEnumerable<T> Traversal<T>(
    T root,
    Func<T, IEnumerable<T>> getChildren)
{
    if (root == null)
    {
        yield break;
    }

    yield return root;

    var children = getChildren(root);
    if (children == null)
    {
        yield break;
    }

    foreach (var child in children)
    {
        foreach (var node in Traversal(child, getChildren))
        {
            yield return node;
        }
    }
}

我喜欢用它

var  classes = Traversal(movie, x => x.similarquestions)

但是它给出了 Whosebug 异常,请知道如何解决这个问题

由于相似性是双向的,您需要保留一个 "visited" 列表并对照它进行检查:

List<Question> visited = new List<Question>();

public static IEnumerable<T> Traversal<T>(
    T root,
    Func<T, IEnumerable<T>> getChildren)
{
    if (root == null)
    {
        yield break;
    }

    //We visited this node!
    visited.Add(root);

    yield return root;

    var children = getChildren(root);
    if (children == null)
    {
        yield break;
    }

    //Don't re-visit nodes we have seen before!
    foreach (var child in children.Except(visited))
    {
        foreach (var node in Traversal(child, getChildren))
        {
            yield return node;
        }
    }
}

还有其他方法可以检查访问过的列表,但这会让您了解如何进行检查。此外,如果它被多次调用,请确保在开始新遍历之前 clear/instantiate 列表!