[英]Searching in recursive Binary Search Tree
我正在使用遞歸在我的二進制搜索樹中搜索元素,但是如果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);
}
}
}
問題
如果root
在以下語句中為nullptr
:
if(root->key==key||root==NULL)
在檢查它是否為NULL
之前,您將首先使用root->key
(它是UB)取消引用空指針。
解決方案
反過來做:
if(root==nullptr||root->key==key)
在這種情況下,如果root為NULL,則立即執行if子句。 僅當root不為NULL時,指針才會被取消引用。
注意: 即使沒有找到該元素,您也知道已找到該元素(即root到達了nullptr,而從未遇到正確的密鑰)。 考慮對nullptr(表示未找到)和相等(表示已找到)分別使用大小寫。
您在這里取消引用NULL指針:
if(root->key==key||root==NULL)
{
cout<<"Congratulation Element found in the BST"<<"\n";
return;
}
||
運算符首先評估左側,如果為value, 則評估右側。 因此,在檢查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);
}
}
您打印得太早了。 如果程序走到葉子,它將打印出來,因為拳頭中的表達式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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.