繁体   English   中英

C++ 二叉搜索树递归搜索功能

[英]C++ Binary Search Tree Recursive search function

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 函数调用了非常量函数,这是一个禁忌。

顺便说一句,这对我来说看起来很可疑“ struct Node<T>*& ”......我可能会放弃 & 并使用Node<T>* ......但也许你因为结构而需要它?

此外,这是 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. 输出 打印消息“找到”或“未找到”。

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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM