Recursion and stackoverflow



我有类似的类

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

为了获得所有的嵌套类,我使用类似的递归方法

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)

但它给了stackoverflow Exception任何关于如何修复的想法,请

由于相似性是双向的,因此需要保留一个"已访问"列表并进行检查:

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

还有其他方法可以检查访问列表,但这会让你知道如何执行。此外,如果多次调用此操作,请确保在开始新的遍历之前清除/实例化列表!

最新更新