C ++二进制搜索树递归搜索功能

时间:2008-10-29 02:44:52

标签: c++ binary-search-tree

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]

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

3 个答案:

答案 0 :(得分:2)

好的,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>*&”......我可能会放弃&amp;并使用Node<T>* ...但是,由于 struct ,您可能需要它吗?

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

答案 1 :(得分:1)

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

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

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

  • 目前还不清楚为何通过引用传递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;
}

答案 2 :(得分:0)

算法:

  1. 获取节点值数据;
  2. 重复步骤3到步骤5,直到找到值或我们超出树。
  3. 如果数据等于根节点值,则搜索成功并终止算法。
  4. 如果数据小于根节点值,我们必须搜索左子树。
  5. 其他数据小于根节点值,我们必须搜索左子树。
  6. 输出打印消息&#34;找到&#34;或&#34;未找到&#34;。
  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);
       }
    
相关问题