How do you implement a recursive walker of a tree with a lazy range?

Benjamin Thaut code at benjamin-thaut.de
Wed Oct 30 08:58:30 PDT 2013


Am 30.10.2013 15:58, schrieb Andrej Mitrovic:
> On 10/30/13, Chris Cain <clcain at uncg.edu> wrote:
>> I'm not confident that this is the most efficient way, but it
>> works.
>
> It allocates, I'm looking for a lazy range. I would be surprised that
> such a common task as iterating a tree is not possible without using
> classes and workarounds.
>

I had this problem too. I just wrote my own range which uses a stack 
internally to remember the nodes that still need to be visited.

When the algorithm hits a non leaf node it pushes the "right" node onto 
the stack and continues with the "left" node. Whenever the algorithm 
hits a leaf node it takes a node from the stack and continues with that. 
That results in a recusion typical depth-first iteration of the nodes.

-- 
Kind Regards
Benjamin Thaut


More information about the Digitalmars-d-learn mailing list