如果我輸出“true”否則“false”,如何檢查(checkV)二叉搜索樹中是否存在值
void search(Node* root, int checkV){
if(checkV > root->data){
search(root->right, checkV);
}
if(checkV < root->data){
search(root->left, checkV);
}
if(checkV == root->data){
cout << "true"<<endl;
}
else{
cout << "false"<<endl;
}
}
uj5u.com熱心網友回復:
如果您需要使用函式“搜索”,那么首先您應該檢查 root 是否指向 nullptr,然后如果您找到資料,然后才應該搜索。像這樣的東西:
void search(Node* root, int checkV) {
if (root->data == nullptr) {
cout << "false" << endl;
}
else if (checkV == root->data) {
cout << "true" << endl;
}
else if (checkV > root->data) {
search(root->right, checkV);
}
else {
search(root->left, checkV);
}
}
但如果你根據那個從搜索和列印結果中回傳 bool 會更好
bool search(Node *root, int checkV) {
if (root == nullptr)
return false;
if (root->data == checkV)
return true;
return root->data < checkV ? check(root->left, checkV) : check(root->right, checkV);
}
uj5u.com熱心網友回復:
我建議你修改你的函式,讓它回傳bool變數。要正確實作該功能,請考慮找不到要查找的節點的情況。在這種情況下,最終您會得到一個nullptr,即Node* root不會指向現有物件。您可以if-else按如下方式構建塊。
bool search(Node* root, int checkV){
if(root == nullptr) return false;
else if(checkV > root->data) return search(root->right, checkV);
else if(checkV < root->data) return search(root->left, checkV);
else if(checkV == root->data) return true; // you can use else as well
}
// Print out true if node exists, otherwise false.
cout << search(root, 5) << endl;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313562.html
上一篇:紅黑樹的性質
