2015-02-04 113 views
0

我上课喜欢递归和计算器

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例外任何想法如何修复请

+0

在调试器中运行它,看看递归是否实际工作。 –

+0

是工作无限 – AMH

+2

如果'问题'指向对方,那么这永远不会终止。 –

回答

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

还有其他的方法来检查对访问列表为好,但是这会给你一个想法如何做到这一点。另外,如果这被多次调用,请务必在开始新的遍历之前清除/实例化列表!