Recursion with yield return elements order in tree

Kornelije Petak picture Kornelije Petak · Feb 3, 2012 · Viewed 8.1k times · Source

I have a recursive function that returns all subtree nodes, given the starting root node.

private IEnumerable<Node> getAllNodesRecursively(Node subnode)
{
    foreach (Node node in subnode.Nodes)
        getAllNodesRecursively(node);

    yield return subnode;
}

For the following tree structure:

A
|
+--B
|
+--C
|  |
|  +--D
|
+--E

When I try to iterate as such:

foreach (Node n in getAllNodesRecursively(a))
{
    Console.WriteLine(n);
}

the function returns the only the A value.

I wish to use yield-return with recursion and retrieve elements in the Preorder (A, B, C, D, E in this example).

(If I put the yield return before the foreach, the foreach would never happen).

Is this possible?

Answer

Joe picture Joe · Feb 3, 2012

Have you tried something like:

private IEnumerable<Node> getAllNodesRecursively(Node subnode) 
{ 
    // Return the parent before its children
    yield return subnode; 

    foreach (Node node in subnode.Nodes) 
    {
        foreach(Node n in getAllNodesRecursively(node))
        {
            yield return n;
        }
    }
} 

Your implementation is calling getAllNodesRecursively recursively, but ignoring its return value.