0

I have class like

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

to get all the nested classes I use recursion using method like

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

I use it like

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

but it give stackoverflow Exception any idea how to fix that please

4
  • Run it in the debugger and see if the recursion is actually working. Commented Feb 4, 2015 at 19:57
  • 2
    If Questions point to each other then this will never terminate. Commented Feb 4, 2015 at 19:59
  • aha got it , so how can solve such a problem ? Commented Feb 4, 2015 at 19:59
  • 2
    Keep a list of questions already traversed and do not process them again. Commented Feb 4, 2015 at 20:01

1 Answer 1

2

Since similarity is bi-directional, you need to keep a "visited" list and check against it:

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

There are other ways to check against the visited list as well, but this will give you an idea of how to do it. Also, if this is being called multiple times, be sure to clear/instantiate the list before starting a new traversal!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.