How Can This Recursive Function Work?
I can't figure out how this work开发者_StackOverflow中文版s, 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;
}
}
}
精彩评论