我正在使用递归在我的二叉搜索树中搜索元素,但如果该元素不在BST中,我的代码将停止工作。
void tree::searching(node *root,int key)
{
if(root->key==key||root==NULL)
{
cout<<"Congratulation Element found in the BST"<<"n";
return;
} else {
if(key<root->key)
{
searching(root->left,key);
} else {
searching(root->right,key);
}
}
}
您在此处取消引用 NULL 指针:
if(root->key==key||root==NULL)
{
cout<<"Congratulation Element found in the BST"<<"n";
return;
}
||
运算符首先评估左侧,如果它是值,则计算右侧。 因此,您在检查root
是否为 NULL 之前取消引用它。
首先执行 NULL 检查,如果找到 NULL 指针,则返回:
void tree::searching(node *root,int key)
{
if (root == nullptr) {
return;
}
if(root->key==key) {
cout<<"Congratulation Element found in the BST"<<"n";
} else if(key<root->key)
searching(root->left,key);
} else {
searching(root->right,key);
}
}
问题
如果root
在此语句中nullptr
:
if(root->key==key||root==NULL)
首先,您将取消引用带有root->key
的空指针,即 UB,然后再检查它是否NULL
。
解决方案
反之亦然:
if(root==nullptr||root->key==key)
在这种情况下,如果 root 为 NULL,则立即执行 if 子句。 仅当 root 不为 NULL 时,才会取消引用指针。
注意:即使找不到元素,您也会告诉该元素已找到(即root到达nullptr,而从未遇到过正确的键(。 考虑对 nullptr(表示未找到它(和相等(表示已找到(具有不同的大小写。
您打印得太早了。如果程序转到叶子,它将打印,因为拳头中的表达式 if 将被计算为 true。
void tree::searching(node *root,int key)
{
if (root == nullptr)
{
return;
}
if(root->key==key)
{
cout<<"Congratulation Element found in the BST"<<"n";
return;
}
else
{
if(key<root->key)
{
searching(root->left,key);
}
else
{
searching(root->right,key);
}
}
}