我正在使用递归在我的二叉搜索树中搜索一个元素,但如果 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;
}
||
运算符首先评估左侧,如果它是值,则然后 评估右侧。因此,在检查它是否为 NULL 之前取消引用 root
。
先做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);
}
}
关于c++ - 在递归二叉搜索树中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52897220/