Say we have the following structure:
struct Tree {
string id;
int numof_children;
Tree *children[5];
};
…where each id is unique (can only appear once in tree), how can I find the path to an id in this type of tree and output it?
I know how to reach the node and check if it exists, but I can’t figure out how to output the proper path.
Restrictions: No vectors/lists/stack data types may be used. Recursion only.
Recommendations: Function look(ATree *t, string &id) should have the return type of a string.
Is there a general structure of recursion that I can follow?
Recursion can be difficult to explain, but I’ll try my best explaining how it applys in this situation. Since you are able to recursively check weither each node exists, you will want to return the id as the return string. This notifies up the recursive stack that a match has been found. You then append the current node’s id to the string and return it up the stack. This in turn notifies up the stack that a match has been found, etc. Here is my solution, which I’ve added multiple comments to better illustrate the point.
Most recursive functions follow a similar pattern. If you still a little lost, I would recommend running it through a debugger so you can see exactly what is going on.