marcelo-ferraz
marcelo-ferraz

Reputation: 3257

Reverse iteraction in a tree-like Object

I have an silly implementation of a tree and its iteration in a regular order.

Something like (the code is merely illustrative):

public IEnumerable<ReferenceNode<TItem, TKey>> AllBellow(ReferenceNode<TItem, TKey> node)
{
    if (/*some codition that tells me that i can return this*/)
    {
        yield return node;
    }
    else 
    {
        foreach (var child in node.Children)
        {
            foreach (var grandChild in AllBellow(child))
            {
                yield return grandChild;
            }
        }
    }
}  

Right, so how could I, starting from the root, reverse the iteration? I mean, instead of going down and from left to right, go down and right to the left...

If the question is not quite clear, please help me straighten it up

Upvotes: 0

Views: 622

Answers (1)

Kaveh Shahbazian
Kaveh Shahbazian

Reputation: 13521

As far as I understood you just need to reverse children:

public IEnumerable<ReferenceNode<TItem, TKey>> AllBellow(ReferenceNode<TItem, TKey> node)
{
    if (/*some codition that tells me that i can return this*/)
    {
        yield return node;
    }
    else 
    {
        foreach (var child in node.Children.Reverse())
        {
            foreach (var grandChild in AllBellow(child))
            {
                yield return grandChild;
            }
        }
    }
}

Upvotes: 1

Related Questions