开发者

iPhone-friendly alternative to recursion over huge tree structures?

开发者 https://www.devze.com 2023-02-28 18:24 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消