iPhone友好的替代递归了巨大的树形结构? [英] iPhone-friendly alternative to recursion over huge tree structures?
本文介绍了iPhone友好的替代递归了巨大的树形结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
予具有相同类型的对象的图。每个对象被链接与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 :)
这篇关于iPhone友好的替代递归了巨大的树形结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文