简体   繁体   中英

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);
   }
  }  
 }

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.

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;
          }   
       }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM