繁体   English   中英

二进制搜索树中是否有子字符串?

[英]Binary Search Tree for substrings?

我有一个有效的搜索功能,可以在数据库中搜索确切的值,但是我的目标是它可以在存储的数据的数据库中以及在搜索子字符串时搜索子字符串(使用cout <<“检查通过”)我可以看到,通过树进行的搜索缩短了,找到了一些子字符串,而其他子字符串更深吗? 为什么?

  bool contains(const Comparable & key, BinaryNode *leaf)
  {
    //cout << "containsing... for: " << key << endl;
    if(leaf != NULL)
    { 
     //std::string Data = leaf->element;

    //cout << "check passed for contains!" << endl;
    if(leaf->element.find(key) != std::string::npos)
    {
       //std::cout << "Found->" << key << "!" << endl;
       return true;
    }
    else if(key >= leaf->element)
    {
     // cout << "key->" << key << "is less than leaf->" <<leaf->element << endl;
      if(leaf->left != NULL)
       return contains(key, leaf->left);
      else
       return false;
    }
    else if(key < leaf->element)
    { 
      //cout << "key->" << key << "is greater than leaf->" <<leaf->element << endl;
      if(leaf->right != NULL)
       return contains(key, leaf->right);
      else
       return false;
    }
    else
      return false;
  }
 else 
  return false;  

} 

尝试这个 ...

bool contains(const Comparable & key, BinaryNode *leaf)
{
    if(!leaf)
        return false;

    if(leaf->element.find(key) != std::string::npos)
        return true;

    int nResult = leaf->element.compare(key);
    if(nResult == 0)
        return true; // This condition will never be hit.
    else
    if(nResult < 0)
        return contains(key, leaf->left)
    else
    if(nResult > 0)
        return contains(key, leaf->right)
}

还尝试调试并查找键值是否小于/大于叶节点值,这是否意味着子字符串也是如此。 如果不是,则必须搜索左右子树。 如果左子树返回false,然后在右子树中搜索。 下面的代码...

bool contains(const Comparable & key, BinaryNode *leaf)
{
    if(!leaf)
        return false;

    if(leaf->element.find(key) != std::string::npos)
        return true;

    if( !contains(key, leaf->left) )
        return contains(key, leaf->right)

    return true;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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