简体   繁体   中英

C++ Function always returns the same pointer

I'm trying to implement a function searching a node from the binary tree and return a Node pointer pointing to the found node like this:

template <class T>
Node<T>* BST<T>::findNode(T a,Node<T>* node)
{
  cout<<node->value<<endl;
  if(a == node->value)
  {
    return node;
  }
  if(a < node->value)
  {
    if(node->left==NULL)
    {
      return NULL;
    }
    findNode(a, node->left);
  }
  if(a > node->value)
  {
    if(node->right==NULL)
    {
      return NULL;
    }
    findNode(a, node->right);
  }
}

In the main program, I have a pointer (called bst)pointing to an instance of Binary Search Tree which is populated with some nodes. And I declared a Node pointer and called the function like this:

    Node <int> * n = bst-> findNode(3,bst->head);

The problem: The function works well if it can't find the matching value, however, if it does find the matching value (ie go the the if(a==node->value) block , it will always return the same value (in my computer, the Node n always get the value of 0x6), how it happened and how to fix that?

TIA!!

您的递归调用实际上并没有返回节点:它们需要看起来像

return findNode(a, node->left);

The function has return statement only for the condition

if(a == node->value)
{
    return node;
}

or for conditions like this

if(node->left==NULL)
{
  return NULL;
}

In all other cases the function has undefined behaviour.

Also this statement in the beginning of the function

cout<<node->value<<endl;

as well as the condition shown above are wrong because in general node can be equal to nullptr .

I would write the function the following way

template <class T>
Node<T>* BST<T>::findNode( Node<T> *node, const T &value )
                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
    if ( node == nullptr || node->value == value )
    {
        return node;
    }
    else if ( node->value < value )
    {
        return findNode( node->right, value );
    }
    else
    {
        return findNode( node->left, value );
    }
}

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