I have this recursive function that generates a tree, when the dictionary is smaller, it works fine, but when the dictionary gets bigger, it throws me a stack overflow exception. I know that I shouldn't be increasing the stack to solve the problem. Is there any idea to optimize this recursive function?
public async static Task<SchemaNodeForGetDto> schemaDecompositionGenerator ( SchemaNodeForGetDto startNode, Dictionary<string, OntologyObjectAttrDictionaryDto> objectsLibrary, Dictionary<string, OntologyObjectPartsDto> objectDecompo, ILogger _logger )
{
//get child of the start node
IEnumerable<OntologyObjectPartDto> decompoParts = objectDecompo[startNode.uri].parts;
IEnumerable<SchemaNodeForGetDto> children = await Task.WhenAll(decompoParts.Select(async x => {
SchemaNodeForGetDto node = new SchemaNodeForGetDto();
node.uri = x.partIri;
node.name = objectsLibrary.ContainsKey(x.partIri) ? objectsLibrary[x.partIri].en : "";
node.constraint = x.constraint;
node.attributes = objectsLibrary.ContainsKey(x.partIri) ? objectsLibrary[x.partIri].attributes : Enumerable.Empty<string>();
//recursive the tree generation
if (objectDecompo.ContainsKey(node.uri)) {
await schemaDecompositionGenerator(node, objectsLibrary, objectDecompo, _logger);
}
// return the child node
return node;
}));
startNode.children = children;
return startNode;
}