fauxCoder
fauxCoder

Reputation: 364

How Can This Recursive Function Work?

I can't figure out how this works, to my mind, once it gets to the answer it doesn't do anything with it.

Node* FindNode(Node *rootNode, int data)
 {
  if (!rootNode)
   return NULL;
  else
  {
   if (rootNode->data == data)
    return rootNode;
   else
   {
    FindNode(rootNode->left, data);
    FindNode(rootNode->right, data);
   }
  }  
 }

Upvotes: 0

Views: 362

Answers (2)

Chubsdad
Chubsdad

Reputation: 25537

This is assuming that the FindNode returns on the first match.

   Node* FindNode(Node *rootNode, int data)
    { 
       Node *ptr;
       if (!rootNode) 
          return NULL; 
       else 
       { 
          if (rootNode->data == data) 
             return rootNode; 
          else 
          {
             ptr = NULL;
             // if either left or right child is there
             if(rootNode->left || rootNode->right)
             { 
                // if not found in left subtree
                if(NULL == (ptr = FindNode(rootNode->left, data))){
                   // check in right subtree
                   ptr = FindNode(rootNode->right, data);
                }
             }
             return ptr;
          }   
       }
    }

Upvotes: 0

David
David

Reputation: 2871

It doesn't. It should be:

Node* FindNode(Node *rootNode, int data) {
    if (!rootNode) {
        return NULL;
    }else if (rootNode->data == data) {
        return rootNode;
    }else if (data < rootNode->data) {
        return FindNode(rootNode->left, data);
    }else{
        return FindNode(rootNode->right, data);
    }
 }

Note the extra return statements, and the extra else if clause.

EDIT — To sum up the comments below: The only reason the code you posted could be working is if an odd combination of compiler-implementation details and test data came together in your favour. You should definitely fix the problem rather than keeping the code how it was.

Upvotes: 10

Related Questions