Thread: quick question about an example in one of the tutorials

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    1

    quick question about an example in one of the tutorials

    In the binary tree tutorial, i am having a little trouble understanding one part of the code.
    Code:
    node *btree::search(int key, node *leaf)
    {
      if(leaf!=NULL)
      {
        if(key==leaf->key_value)
          return leaf;
        if(key<leaf->key_value)
          return search(key, leaf->left);
        else
          return search(key, leaf->right);
      }
      else return NULL;
    }
    why is it neccessary to use node(a struct) as the return type? (rest of the code is in tutorial, too long to post )
    instead of using something like this, and changing the rest of the code to match it.

    Code:
    int *btree::search(int key, node *leaf)
    {
      if(leaf!=NULL)
      {
        if(key==leaf->key_value)
          return leaf;
        if(key<leaf->key_value)
          return search(key, leaf->left);
        else
          return search(key, leaf->right);
      }
      else return NULL;
    }
    just curious, all i need is to be pointed in the right direction, thanks in advance

  2. #2
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    If you return the node pointer, it makes recursion easy. What sort of int pointer would you have it return? If you did return an int as some sort of identifier, you would have to re-search the list to find the int, which would lead to bad recursion, seeing as this is a search function.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. quick question (adding characters)
    By Cactus in forum C Programming
    Replies: 2
    Last Post: 09-24-2005, 03:54 PM
  2. very quick question.
    By Unregistered in forum C++ Programming
    Replies: 7
    Last Post: 07-24-2002, 03:48 AM
  3. quick question
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 07-22-2002, 04:44 AM
  4. Quick Question Regarding Pointers
    By charash in forum C++ Programming
    Replies: 4
    Last Post: 05-04-2002, 11:04 AM
  5. Quick question: exit();
    By Cheeze-It in forum C Programming
    Replies: 6
    Last Post: 08-15-2001, 05:46 PM