I have this code which iterates over a tree, doing a depth-first search. Every element is tackled exactly once. Very good.
-(void)iterateOverTree:(TreeNode *)node
{
NSMutableArray * elements = [NSMutableArray array];
[elements addObject:node];
while([elements count])
{
TreeNode * current = [elements objectAtIndex:0];
[self doStuffWithNode:current];
for(TreeNode * child in current.children)
{
[elements addObject:child];
}
[elements removeLastObject];
}
}
BUT: How can I keep track of the current depth in the graph? I need to know the level of depth. So for example I have these nodes:
A has childs B, J. B has child C. C has child D. D has childs E, F, I.
When A is at depth level 1, then B is 2 and C is 3.
With recursion it was very easy to keep track of the current depth level. Just inrement a variable before calling itself and decrement it after calling itself.
But here with this fancy while loop that is not possible. There is no box in the box in the box happening like with recursion.
I don't really want to have to add properties (or instance variables) to the TreeNode object as this should be re-usable in a generic way for any kind of object graph.
Does anyone have an idea how to do this? Must I introduce another array to keep track of visited nodes?