【问题标题】:How can I check(checkV) if a value exists in Binary search tree if does I output "true" else "false"如果我输出“true”否则“false”,如果二进制搜索树中存在值,我如何检查(checkV)
【发布时间】:2021-11-29 16:30:33
【问题描述】:

如果我输出“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;
    }
}

【问题讨论】:

  • 这段代码有什么问题?乍一看还不错。
  • 当我们正在寻找具有给定int 值的节点时,它会出错。我们必须添加nullptr 检查。

标签: c++ algorithm data-structures binary-search-tree


【解决方案1】:

如果你需要使用“搜索”功能,那么首先你应该检查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);
}

【讨论】:

    【解决方案2】:

    我建议你修改你的函数,让它返回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;  
    

    【讨论】:

    • 递归调用需要返回。即return search(...).
    猜你喜欢
    • 2011-08-11
    • 2016-01-04
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多