📜  递归搜索一个特里

📅  最后修改于: 2021-04-22 00:25:12             🧑  作者: Mango

Trie是一种有效的信息检索数据结构。使用Trie,可以使搜索复杂度达到最佳极限(密钥长度)。
任务是使用递归在Trie中搜索字符串。
例子 :

root
                                         /  \    
                                         t   a     
                                         |   |     
                                         h   n     
                                         |   |  \  
                                         e   s   y  
                                      /  |   |
                                     i   r   w
                                     |   |   |
                                      r  e   e
                                             |
                                             r

Input : str = "anywhere"                                      
Output : not found

Input : str = "answer"                                      
Output : found

方法 :
搜索键类似于插入操作,但是,我们仅比较字符并向下移动。搜索可能由于字符串或Trie中缺少关键字而终止。在前一种情况下,如果最后一个节点的endOfWord字段为true,则该键存在于trie中。在第二种情况下,搜索将终止,而不检查键的所有字符,因为该键不在Trie中。
下面是上述方法的实现:

CPP
// CPP program to search in a trie
#include 
using namespace std;
#define CHILDREN 26
#define MAX 100
 
// Trie node
struct trie {
    trie* child[CHILDREN];
    // endOfWord is true if the node represents
    // end of a word
    bool endOfWord;
};
 
// Function will return the new node(initialized to NULLs)
trie* createNode()
{
    trie* temp = new trie();
    temp->endOfWord = false;
    for (int i = 0; i < CHILDREN; i++) {
        // initially assign null to the all child
        temp->child[i] = NULL;
    }
    return temp;
}
/*function will insert the string in a trie recursively*/
void insertRecursively(trie* itr, string str, int i)
{
    if (i < str.length()) {
        int index = str[i] - 'a';
        if (itr->child[index] == NULL) {
 
            // Insert a new node
            itr->child[index] = createNode();
        }
        // Recursive call for insertion of a string
        insertRecursively(itr->child[index], str, i + 1);
    }
    else {
        // Make the endOfWord true which represents
        // the end of string
        itr->endOfWord = true;
    }
}
// Function call to insert a string
void insert(trie* itr, string str)
{
    // Function call with necessary arguments
    insertRecursively(itr, str, 0);
}
 
// Function to search the string in a trie recursively
bool searchRecursively(trie* itr, char str[], int i,
                                               int len)
{
    // When a string or any character
    // of a string is not found
    if (itr == NULL)
        return false;
 
    // Condition of finding string successfully
    if (itr->endOfWord == true && i == len - 1) {
        // Return true when endOfWord
        // of last node containes true
        return true;
    }
 
    int index = str[i] - 'a';
    // Recursive call and return
    // value of function call stack
    return searchRecursively(itr->child[index],
                                   str, i + 1, len);
}
 
// Function call to search the string
void search(trie* root, string str)
{
    char arr[str.length() + 1];
    strcpy(arr, str.c_str());
    // If string found
    if (searchRecursively(root, arr, 0, str.length() + 1))
        cout << "found" << endl;
 
    else {
        cout << "not found" << endl;
    }
}
 
// Driver code
int main()
{
    trie* root = createNode();
 
    // Function call to insert the string
    insert(root, "thier");
    insert(root, "there");
    insert(root, "answer");
    insert(root, "any");
 
    // Function call to search the string
    search(root, "anywhere");
    search(root, "answer");
 
    return 0;
}


Python3
# Python3 program to traverse in bottom up manner
CHILDREN = 26
MAX = 100
 
# Trie node
class trie:
 
    def __init__(self):
        self.child = [None for i in range(CHILDREN)]
         
        # endOfWord is true if the node represents
        # end of a word
        self.endOfWord = False
 
# Function will return the new node(initialized to NULLs)
def createNode():
 
    temp = trie()
    return temp
 
# Function will insert the string in a trie recursively
def insertRecursively(itr, str, i):
 
    if(i < len(str)):
     
        index = ord(str[i]) - ord('a')
         
        if(itr.child[index] == None ):
         
            # Insert a new node
            itr.child[index] = createNode();
         
        # Recursive call for insertion of string
        insertRecursively(itr.child[index], str, i + 1);
     
    else:
     
        # Make the endOfWord true which represents
        # the end of string
        itr.endOfWord = True;
     
# Function call to insert a string
def insert(itr, str):
 
    # Function call with necessary arguments
    insertRecursively(itr, str, 0);
  
# Function to search the string in a trie recursively
def searchRecursively(itr ,str, i, len):
 
    # When a string or any character
    # of a string is not found
    if (itr == None):
        return False
 
    # Condition of finding string successfully
    if (itr.endOfWord == True and i == len - 1):
         
        # Return true when endOfWord
        # of last node containes true
        return True
     
    index = ord(str[i]) - ord('a')
 
    # Recursive call and return
    # value of function call stack
    return searchRecursively(itr.child[index], str, i + 1, len)
 
# Function call to search the string
def search(root, str):
 
    arr = ['' for i in range(len(str) + 1)]
    arr = str
     
    # If string found
    if (searchRecursively(root, arr, 0, len(str) + 1)):
        print("found")
    else:
        print("not found")
 
# Driver code
if __name__=='__main__':
     
    root = createNode();
     
    # Function call to insert the string
    insert(root, "thier");
    insert(root, "there");
    insert(root, "answer");
    insert(root, "any");
     
    # Function call to search the string
    search(root, "anywhere")
    search(root, "answer")
  
# This code is contributed by rutvik_56


输出:
not found
found