gpt4 book ai didi

c++ - 在二叉搜索树中查找元素仅在 true 时有效

转载 作者:太空宇宙 更新时间:2023-11-04 14:59:19 24 4
gpt4 key购买 nike

当我向我的 bst 发送查询以根据是否找到元素返回 t/f 值时,它在 true 时正常工作,但当元素不在 bst 中时会导致延迟崩溃。

我这辈子都想不通。

.cpp

bool BinarySearchTree::find(std::string title){

if (root == NULL)
return 0;

return findHelper(root,title);
}

bool BinarySearchTree::findHelper(Node* current, std::string title){

if (current->title.compare(title) == 0)
return 1;

if (current->title.compare(title) < 0)
findHelper(current->left, title);
else
findHelper(current->right, title);

return 0;
}

主要

if (select == 4) {

bool x;

string s;

cout << "Enter Title: " << endl;

cin.ignore();
getline(cin, s);

x = t.find(s);
if (x)
cout << "found" << endl;
else
cout << "unfound" << endl;

printMenu();

cout << "Enter Choice: ";

cin >> select;

}

谢谢。

最佳答案

当你进行递归时,你应该返回递归调用返回的任何内容,而不是 0。只有到达树的末尾时才返回 0。

bool BinarySearchTree::findHelper(Node* current, std::string title)
{
if (current == nullptr)
return 0;

if (current->title.compare(title) == 0)
return 1;

if (current->title.compare(title) < 0)
return findHelper(current->left, title);
else
return findHelper(current->right, title);
}

关于c++ - 在二叉搜索树中查找元素仅在 true 时有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59206473/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com