template <class T>
bool BST<T>::search(const T& x, int& len) const
{
    return search(BT<T>::root, x);
}


template <class T>
bool BST<T>::search(struct Node<T>*& root, const T& x)
{
   if (root == NULL)
       return false;
   else
      {
         if (root->data == x)
             return true;
         else if(root->data < x)
             search(root->left, x);
         else 
             search(root->right, x);                 
      }             
}

这是我的带有 T 节点的 BST 类的搜索函数。x 是在树中搜索的数据,len 只是为了找到匹配节点(如果存在)而必须经过的节点数量。我还没有实施这一点,我只是逐步开发我的任务。我通过这样做来调用它:

if(t.search(v[1], len) == true)
       cout << endl << "true";

v 只是我必须创建的一个向量来比较它,所以这只是为其提供一个 int 。我收到的错误:

BST.h: In member function âbool BST<T>::search(const T&, int&) const [with T = int]â:
prog5.cc:24:   instantiated from here    
BST.h:78: error: no matching function for call to âBST<int>::search(Node<int>* const&, const int&) constâ    
BST.h:76: note: candidates are: bool BST<T>::search(const T&, int&) const [with T = int]
BST.h:83: note:                 bool BST<T>::search(Node<T>*&, const T&) [with T = int]

所以我不确定我做错了什么或者哪里做错了。

有帮助吗?

解决方案

好的,bool BST<T>::search(struct Node<T>*& root, const T& x)应该像以后一样有const:bool BST<T>::search(struct Node<T>*& root, const T& x) const。基本上,你从const函数调用了一个非const函数,这是一个禁忌。

顺便说一下,这对我来说很可疑<!>“struct Node<T>*& <!>”... ...我可能会放弃<!>放大器;并使用Node<T>* ...但是,由于 struct ,您可能需要它吗?

此外,这是C ++,没有理由将Node作为结构...需要在参数定义中使用 struct 看起来很糟糕,恕我直言。为什么不让Node成为一个类?

其他提示

您的搜索代码存在多个问题:

  • 排序顺序是向后的,如果节点数据小于您搜索的数据,您应该在右分支中搜索,而不是左分支。

  • 您应该返回递归调用的结果

  • 也不清楚你为什么通过 root 引用。它应该作为 const 合格的指针和方法体应该是 const 也有资格。

这是一个替代方案:

template <class T>
bool BST<T>::search(const struct Node<T> *root, const T& x) const {
    if (root == NULL)
        return false;
    else
    if (root->data == x)
        return true;
    else
    if (root->data < x)
        return search(root->right, x);
    else 
        return search(root->left, x);
}

这是一个更简单的非递归实现:

template <class T>
bool BST<T>::search(const struct Node<T> *root, const T& x) const {
    while (root != NULL) {
        if (root->data == x)
            return true;
        if (root->data < x)
            root = root->right;
        else 
            root = root->left;
    }
    return false;
}

算法:

  1. 获取节点值数据;
  2. 重复步骤3到步骤5,直到找到值或我们超出树。
  3. 如果数据等于根节点值,则搜索成功并终止算法。
  4. 如果数据小于根节点值,我们必须搜索左子树。
  5. 其他数据小于根节点值,我们必须搜索左子树。
  6. 输出打印消息<!>“;找到<!>”;或<!>“;未找到<!>”;

  7. C ++实现

        node* search(node* root, int data)
        {
         if (root==NULL || root->data==data) return root;
    
         if (root->data < data)   return search(root->right, data);
    
         return search(root->left, data);
       }
    
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top