二叉搜索树:搜索功能问题

Binary Search Tree: Search Function Issue

本文关键字:功能 问题 搜索 搜索树      更新时间:2023-10-16

我已经实现的搜索功能有点工作。当我搜索不存在的值时,搜索函数会查找并返回 false。当我搜索一个作为根的值时,它工作正常并返回 true。问题是当我搜索树中已经存在的根以外的值时,但它返回 false。关于我做错了什么的任何想法?

template <class Comparable>
bool BinarySearchTree<Comparable>::findValue(const Comparable& value){
if(root->element == value){
    return true;
}
if(value > root->element)
{
    if(root->right != NULL)
    {
        root->right->findValue(value);
    }
    else
    {
        return false;
    }
}
if(value < root->element)
{
    if(root->left != NULL)
    {
    root->left->findValue(value);
    }
    else
    {
        return false;
    }
这些

是我的私人数据成员,这些不能以任何方式更改。

private:
struct BinaryNode
{
    Comparable element;
    BinarySearchTree<Comparable> *left;
    BinarySearchTree<Comparable> *right;
};
BinaryNode *root;
};

当你从右节点return false时,你甚至从不尝试左节点。

尝试返回 true;

if(value > root->element)
{
    if(root->right != NULL)
    {
        if(root->left->findValue(value))
        {  
            return true;
        }
    }
}
if(value < root->element)
{
    if(root->left != NULL)
    {
        if(root->left->findValue(value)
        {  
            return true;
        }
    }
}
return false

你应该返回 root->left->findValue(value);root->right->findValue(value) 的结果

当前,您正在为这些节点调用 findValue 函数,但不存储值或将其返回到任何位置,因此结果会丢失。