予具有相同类型的对象的图。每个对象被链接与0,1或许多其他问题。我需要遍历图中的所有可能的路径。
I have a graph of objects of the same type. Every object is linked with 0, 1 or many others. 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?
线沿线的东西:
(我们presume树节点包含属性的NSArray *儿童)
(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];
}
}
当心,未经测试code:)
Beware, untested code :)