在二叉搜索树中查找元素

Finding an element in Binary Search Tree

本文关键字:查找 元素 搜索树      更新时间:2023-10-16

我写这段代码是为了在BST中查找一个节点。代码适用于找到的节点,但找不到节点时代码崩溃。

我的代码中可能出现什么错误?

 TreeNode* fetch(TreeNode*root,int d)
    {
                if(root->data==d)
                {
                    return root;
                }
               else  if(root==NULL)
                {
                    return NULL;
                }
                else if(d<root->data)
                {
                    return fetch(root->left,d);
                }
                else if(d>root->data)
                {
                    return fetch(root->right,d);
                }
    }
   TreeNode* temp;
   temp=fetch(root,d);
   if(temp->data)
  {
        cout<<temp->data<<" FOUND";
    }
else if(temp==NULL)
{
    cout<<"Not Found";
}

你需要在 fetch(( 函数中调整你的排序。现在,如果 root==NULL 会出错,因为它首先检查潜在不存在的节点中的数据是否等于 d 。固定如下:

TreeNode* fetch(TreeNode*root,int d)
{
            if(root==NULL)
            {
                return NULL;
            }
           else  if(root->data==d)
            {
                return root;
            }
            else if(d<root->data)
            {
                return fetch(root->left,d);
            }
            else if(d>root->data)
            {
                return fetch(root->right,d);
            }
}
此外,出于

同样的原因,您需要在底部重新订购支票:

if(temp==NULL)
  {
       cout<<"Not Found"; 
    }
else
{
    cout<<temp->data<<" FOUND";
}

问题在于如果梯子,则输入条件的顺序。

请阅读我在您的代码行上写

的评论
 TreeNode* fetch(TreeNode*root,int d)
        {
                    if(root->data==d)   /* if d doesn't exists, root becomes 
                                         null and dereferencing a null 
                                         gives error, i.e, null->data is 
                                         error. So, first root=null should 
                                         be checked*/
                    {
                        return root;
                    }
                   else  if(root==NULL)
                    {
                        return NULL;
                    }
                    else if(d<root->data)
                    {
                        return fetch(root->left,d);
                    }
                    else if(d>root->data)
                    {
                        return fetch(root->right,d);
                    }
        }
       TreeNode* temp;
       temp=fetch(root,d);
       if(temp->data)    // temp=NULL should be must codition
      {
            cout<<temp->data<<" FOUND";
        }
    else if(temp==NULL)
    {
        cout<<"Not Found";
    }
如果

节点是叶子,则没有案例。在调用fetch(root->left,d)fetch(root->right,d)之前,在再次调用 fetch 之前,通过检查 if(root->(左/右(!= NULL( 来确保节点具有左元素或右元素。如果他们执行 == NULL,那么您可以在导航到树的底部并且没有找到您的元素时返回 NULL。