views:

44

answers:

2

Hi,

I have a recursive function that is designed to take parse a tree and store all the values of the tree nodes in an NSString.

Is the algorithm below correct?

NSString* finalString = [self parseTree:rootNode string:@""];

-(NSString*)parseTree:(Node*)currentNode string:(NSMutableString*)myString
{
    [myString appendText:currentNode.value];

    for(int i=0;i<[currentNode.children length];i++){
        return [self parseTree:[currentNode.children] objectAtIndex:i] string:myString];
    }
}
A: 

No, not really.

ivans
+7  A: 

No, it is not.

  1. You pass in @"" as the starting string. However, @"" is not an NSMutableString. This will certainly produce an exception when run.
  2. As soon as you return, then that method stops and you don't execute any more. This means that you go through the first iteration of the loop, you'll stop. Forever.
  3. You don't return anything if there are no children in the currentNode.
  4. There's no such method as appendText:. You probably mean appendString:

Here's another question: Why do you need to return a value at all? You're passing in an NSMutableString and modifying it, so why not just always modify it in place and not bother with a return value? For example:

- (void) parseTree:(Node*)currentNode string:(NSMutableString*)myString {
    [myString appendString:currentNode.value];

    for(Node * child in [currentNode children]){
        [self parseTree:child string:myString];
    }
}

And then invoke this with:

NSMutableString * finalString = [NSMutableString string];
[self parseTree:aNode string:finalString];
Dave DeLong
+1 for going above and beyond what the original poster asked :)
ivans