如何在二叉搜索树中查找元素

How to find an element in a binary search tree?

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

我一直在尝试构建一个 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 函数将只返回垃圾(堆栈上临时分配的地址)。

顺便说一下,一个体面的编译器应该为此发出警告。