And there could be many levels, who knows how deep it could go! Also let’s say for this specific question that the String for another Dictionary will be “Dictionary” and a value that I want to access/modify will be “Data”.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No. Any recursive algorithm can be rewritten to use an explicit stack rather than the call stack.
Perhaps. However, if the structure is very deeply nested (or contains cycles) you can run the risk of a stack overflow exception.
The non-recursive implementation is not particularly hard to implement. It would require you to maintain a list (a stack or queue, depending on what order you want to visit children in) that keeps track of the sub-dictionaries yet to be visited.
A prototypical (non-recursive) implementation would look something like:
The implementation above does no error checking and it doesn’t check for cycles, but it replaces recursion with an explicit stack.
The choice of whether to use recursion (or not) for visiting a hierarchical data structure should depend on an understanding of the kind of data being stored rather than which approach is easier. If you have a deeply nested structure, you are better off NOT using recursion since you can’t control how much stack space you’ll have available. On the other hand, if you are confident that the data will never nest more than a few level, a recursive implementation may be (slightly) easier to understand and maintain.