[英]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: 我正在尝试实现一个从二叉树中搜索节点并返回指向所找到节点的Node指针的功能,如下所示:
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. 在主程序中,我有一个指针(称为bst)指向二进制搜索树的实例,该实例中填充了一些节点。 And I declared a Node pointer and called the function like this:
我声明了一个Node指针,并像下面这样调用了函数:
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? 问题:如果找不到匹配的值,该函数会很好地工作,但是,如果找到匹配的值(即,通过
if(a==node->value) block
,它将始终返回相同的值(在我的计算机中,节点n始终获得0x6的值),它是如何发生的以及如何解决的?
TIA!! 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
. 以及上面显示的条件是错误的,因为通常
node
可以等于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 );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.