递归和stackoverflow

时间:2015-02-04 19:55:51

标签: c# recursion

我喜欢上课

 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异常任何想法如何解决这个问题

1 个答案:

答案 0 :(得分:2)

由于相似性是双向的,因此您需要保留“已访问”列表并对其进行检查:

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

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