0

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?

DillPixel
  • 955
  • 1
  • 14
  • 20

1 Answers1

0

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.

// If found return [string] [of] [ids], else empty string
string look(const Tree * t, const string & id) {
   // If current node matchs return id
   if(t->id == id) {
      return "[" + id + "]";
   }

   // Loop over each child, recursively calling look
   for(int i=0; i<t->numof_children; i++) {
      string s = look(t->children[i], id);
      // If found add to string and return
      if(!s.empty()) {
         return "[" + t->id + "] " + s;
         // alternatively: return s + " [" + t->id + "]"; will genreate string in reverse
      }
   }

   // Not found, return empty string
   return string();
}

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.

Tyler Hyndman
  • 1,402
  • 3
  • 17
  • 24
  • This is very helpful, you make it seem so simple. I always struggle with recursion, I can't visualize how it works unless it's something very simple... Do you have any advice for the future? – DillPixel Nov 02 '11 at 04:07
  • Take a look at Structure and Interpretation of Computer Programs. It's freely available and there are lectures online. In the first chapter they have a good description of recursion. This [answer](http://stackoverflow.com/questions/1711/what-is-the-single-most-influential-book-every-programmer-should-read/29433#29433) has all the information you need about the book. – Tyler Hyndman Nov 02 '11 at 14:17