简体   繁体   中英

Binary Search Tree for substrings?

I have a working search function that will search for the exact value in a database, but my goal is for it to search for substrings in the database of the stored data and when searching for substrings (having used cout << "check passed") I can see that the search through the tree cuts short, some substrings get found, others deeper in don't? Why?

  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;  

} 

Try this ...

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

Also try to debug and find if a key value is less than/ greater than the leaf node value then does this mean that it is the same for the substring as well. If not then you have to search both left and right sub trees. IF left sub tree returns false then search in right sub tree. Code below ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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