Return NSString from a recursive function
I have a recursive function that is designed to take parse a tree and store all the v开发者_开发知识库alues 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];
}
}
No, it is not.
- You pass in
@""
as the starting string. However,@""
is not anNSMutableString
. This will certainly produce an exception when run. - 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. - You don't return anything if there are no children in the currentNode.
- There's no such method as
appendText:
. You probably meanappendString:
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];
精彩评论