在二叉搜索树中查找元素
Finding an element in Binary Search Tree
我写这段代码是为了在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。
相关文章:
- 在对向量中查找元素的索引
- 在链接列表中查找元素 - C++
- 在数组中查找元素,如果找到则返回Find,否则返回not Find
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 用于查找元素的数据结构
- 为什么在查找元素时需要使用 set.find(x) != set.end()
- 在二叉搜索树中查找元素
- 二进制搜索不变以查找元素的首次出现
- 迭代列表以查找元素的出现.代码问题
- 从单链接列表(从尾部)中查找元素
- iMacro 查找元素
- 在向量数组中查找元素
- 如何在二叉搜索树中查找元素
- 如何在字符右侧的QString中查找元素
- 在Vector中查找元素对
- 如何在运行时在boost::fusion::vector中查找元素
- 在 stl 堆栈 cpp 中查找元素
- 在向量中查找元素并将其删除
- 如何在动态数组中查找元素的数量
- 在数组中查找元素,然后使用指针进行交换