I have a graph of objects of the same type. Every object is linked with 0, 1 or many others开发者_JAVA技巧. I need to walk through all possible paths in the graph.
Now I could do that with recursion, but there is the danger of a stack overflow. There can be tens of thousands of them.
I've heard there are better ways than recursion where a method keeps calling itself over and over again.
What do the alternatives look like?
Something along the lines of:
(let's presume TreeNode contains a property NSArray * children)
-(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 removeObjectAtIndex:0];
}
}
Beware, untested code :)
You can "imitate" stack by yourself, storing current state in a NSArray. That will allow to use heap instead of stack memory and, possibly, workaround stack overflow issue.
精彩评论