How to modify this tree iteration code to iterate in an ordered way?
This piece of code iterates over a tree of TreeNode objects where every object may have childs (from an Answer to this question: iPhone-friendly alternative to recursion over huge tree structures?).
-(void)iterateOverTree:(TreeNode *)node
{
NSMutableArray * elements = [NSMutabl开发者_开发技巧eArray 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 removeObjectAtIndex:0];
}
}
The problem is that this code does not walk through the tree in an ordered way.
i.E. I have this: A owns B, J B owns C owns D owns E J owns K owns L owns M (note: "owns" means "has child". A has two childs while the rest has one or none)
This is how the tree is traversed: A, B, J, C, K, D, L, ...
But I want: A, B, C, D, E, J, K, L, M, ...
in an ordered way, just like it happens with recursion.
How could I change that in such a way that it traverses the tree ordered, like in the example above?
You want depth first search. Currently you're performing breadth first search.
I don't know Objective-C, but it looks like you're using NSMutableArray as a queue. Use it as a stack for non-recursive depth first search.
精彩评论