1

I have a method that looks like:

    public IEnumerable<Node> TraverseTree(Node root)
    {            
        if(root.Children != null)
        {
            foreach(var item in root.Children)
                TraverseTree(item);
        }

        yield return root;
    }

and when I do:

var allItems = TraverseTree(someRootNode).ToList(); 

I only get the first node. Is it not possible to use recursion when using IEnumerable? It will be nice if I can use IEnumerable so that my linq queries do not fully execute.

Edit

Sorry my Node class looks like:

class Node
{
     public Node Val;
     public List<Node> Children = new List<Node>();
}
Tono Nam
  • 34,064
  • 78
  • 298
  • 470
  • Similar: http://stackoverflow.com/questions/11830174/how-to-flatten-tree-via-linq – Jacob G Apr 26 '13 at 19:55
  • I found a similar solution at: http://stackoverflow.com/a/1043363/637142 I like aquaraga solution better though ;) – Tono Nam Apr 26 '13 at 19:56

1 Answers1

2

It could be rewritten as:

    public IEnumerable<Node> TraverseTree(Node root)
    {
        if (root.Children != null)
        {
            foreach (var child in root.Children)
            {
                var nodes = TraverseTree(child);
                foreach (var node in nodes)
                {
                    yield return node;
                }
            }
        }

        yield return root;
    }
aquaraga
  • 4,138
  • 23
  • 29