【问题标题】:Binary Search Tree: Search Function Issue二叉搜索树:搜索功能问题
【发布时间】:2014-02-19 23:06:25
【问题描述】:

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

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;
};

【问题讨论】:

    标签: c++ search root binary-search-tree


    【解决方案1】:

    当你从右节点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
    

    【讨论】:

    • 我已经尝试了你所说的,我得到了相同的结果。
    【解决方案2】:

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

    目前您正在为这些节点调用 findValue 函数,但没有存储该值或将其返回到任何地方,因此结果会丢失。

    【讨论】:

    • 我已经尝试过你所说的,但它仍然无法正常工作抱歉,这是使用正确的 pastebin 进行的编辑pastebin.com/CQhAw7CF
    猜你喜欢
    • 2019-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多