当我向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;

}


谢谢。

最佳答案

问题是您永远不会检查是否遇到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;
}

10-08 08:09
查看更多