开发者社区> 问答> 正文

在二进制搜索树中查找元素时才能工作

当我向我的BST发送一个查询以返回一个t/f值时,是否找到了这个元素,它在正确的情况下正常工作,但是当元素不在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;
}
main

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;

}

谢谢。

展开
收起
aqal5zs3gkqgc 2019-12-06 20:15:14 979 0
1 条回答
写回答
取消 提交回答
  • 问题是,您从未检查是否遇到了nullptr。

    像这样的事情可以解决这个问题:

    bool BinarySearchTree::findHelper(Node* current, std::string title){
    
        if (current->title.compare(title) == 0)
            return 1;
    
        if (current->title.compare(title) < 0 && current->left != nullptr)
        {
            return findHelper(current->left, title);
        }
        else if(current->right != nullptr)
        {
            return findHelper(current->right, title);
        }
        return 0;
    }
    
    2019-12-06 20:15:43
    赞同 展开评论 打赏
问答分类:
C++
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载