如果我输出"true" else "false",我如何检查(checkV)二进制搜索树中是否存在值
How can I check(checkV) if a value exists in Binary search tree if does I output "true" else "false"
如果我输出“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;
}
}
我建议您修改函数,使其 returns 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;
如果你需要使用“搜索”功能,那么首先你应该检查根是否指向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);
}
}
但是,如果您 return 从搜索中布尔并根据
打印结果会更好
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);
}
如果我输出“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;
}
}
我建议您修改函数,使其 returns 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;
如果你需要使用“搜索”功能,那么首先你应该检查根是否指向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);
}
}
但是,如果您 return 从搜索中布尔并根据
打印结果会更好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);
}