如何在二叉搜索树中查找元素
How to find an element in a binary search tree?
我一直在尝试构建一个 2-3 节点。添加功能工作正常,到目前为止已得到我的确认。唯一的问题是 find 函数,调用它是为了查找 2-3 节点内的元素。它似乎根本不起作用。it 中的匹配指针根本不从 find_rec
方法中获取返回的值,即使我已经分配了它。每当调用函数时,它都会获得一个新的给定地址,我不知道它为什么这样做。谁能帮我?并告诉我我做错了什么?谢谢
**LValue and RValue**
E LValue() {return _first._value;}
E RValue() {return _second._value;}
**find function**
// Assuming this set contains an element y such that (x == y),
// return a reference to y. Such a y must exist; if it does not an
// assertion will fail.
E& find(E& x)
{
// the match pointer is supposed to take
// returned pointer from the find_rec function
// Yet, it is not doing that at all.
E* match = find_rec(x, _root);
assert(match != nullptr);
return *match;
}
**find_rec function**
// Helper function: find recursion
// function returns a pointer
E* find_rec(E& x, BNode<E>* root)
{
if(root == nullptr)
return nullptr;
else
{
// 2-node
if(!root->IsThree())
{
if(x == root->LValue())
return &root->LValue();
else if (x < root->LValue())
return find_rec(x, root->GetLeft());
else
return find_rec(x, root->GetRight());
}
// 3-node
else
{
if(x == root->LValue())
return &root->LValue();
else if(x == root->RValue())
return &root->RValue();
else if(x < root->LValue())
return find_rec(x, root->GetLeft());
else if(x < root->RValue())
return find_rec(x, root->GetMiddle());
else
return find_rec(x, root->GetRight());
}
}
}
当树中不存在所需的值时,代码显然能够返回 nullptr。
一旦它进入这种情况,断言将触发,*match
返回将失败。我希望您需要更改函数签名以提供允许这种情况的返回类型。
从代码来看,您似乎正在返回本地临时地址。
我不确定,因为LValue()
方法声明不可见,但如果它按值而不是按引用返回节点内容,那么 find_rec
函数将只返回垃圾(堆栈上临时分配的地址)。
顺便说一下,一个体面的编译器应该为此发出警告。
相关文章:
- 在对向量中查找元素的索引
- 在链接列表中查找元素 - C++
- 在数组中查找元素,如果找到则返回Find,否则返回not Find
- 在给定元素在螺旋上的位置的情况下,在二维数组中查找元素
- 用于查找元素的数据结构
- 为什么在查找元素时需要使用 set.find(x) != set.end()
- 在二叉搜索树中查找元素
- 二进制搜索不变以查找元素的首次出现
- 迭代列表以查找元素的出现.代码问题
- 从单链接列表(从尾部)中查找元素
- iMacro 查找元素
- 在向量数组中查找元素
- 如何在二叉搜索树中查找元素
- 如何在字符右侧的QString中查找元素
- 在Vector中查找元素对
- 如何在运行时在boost::fusion::vector中查找元素
- 在 stl 堆栈 cpp 中查找元素
- 在向量中查找元素并将其删除
- 如何在动态数组中查找元素的数量
- 在数组中查找元素,然后使用指针进行交换