繁体   English   中英

在递归二进制搜索树中搜索

[英]Searching in recursive Binary Search Tree

我正在使用递归在我的二进制搜索树中搜索元素,但是如果BST中不存在该元素,我的代码将停止工作。

void tree::searching(node *root,int key)
{
    if(root->key==key||root==NULL)
    {
       cout<<"Congratulation Element found in the BST"<<"\n";
       return;
    } else {
        if(key<root->key)
        {
           searching(root->left,key);
        } else {
           searching(root->right,key);
        }
    }
}

问题

如果root在以下语句中为nullptr

    if(root->key==key||root==NULL)

在检查它是否为NULL之前,您将首先使用root->key (它是UB)取消引用空指针。

解决方案

反过来做:

    if(root==nullptr||root->key==key)

在这种情况下,如果root为NULL,则立即执行if子句。 仅当root不为NULL时,指针才会被取消引用。

注意: 即使没有找到该元素,您也知道已找到该元素(即root到达了nullptr,而从未遇到正确的密钥)。 考虑对nullptr(表示未找到)和相等(表示已找到)分别使用大小写。

您在这里取消引用NULL指针:

if(root->key==key||root==NULL)
{
    cout<<"Congratulation Element found in the BST"<<"\n";
    return;
}

|| 运算符首先评估左侧,如果为value, 评估右侧。 因此,在检查root是否为NULL之前,请先取消对其的引用。

首先执行NULL检查,如果找到NULL指针则返回:

void tree::searching(node *root,int key)
{
    if (root == nullptr) {
        return;
    }

    if(root->key==key) {
        cout<<"Congratulation Element found in the BST"<<"\n";
    } else if(key<root->key)
        searching(root->left,key);
    } else {
        searching(root->right,key);
    }
}

您打印得太早了。 如果程序走到叶子,它将打印出来,因为拳头中的表达式if将被评估为true。

void tree::searching(node *root,int key)
{
    if (root == nullptr)
    {
        return;
    }
    if(root->key==key)
    {
        cout<<"Congratulation Element found in the BST"<<"\n";
        return;
    }
    else
    {
        if(key<root->key)
        {
            searching(root->left,key);
        }
        else
        {
            searching(root->right,key);
        }
    }

 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM