Trie is an efficient information retrieval data structure. Using Trie, search complexities can be brought to an optimal limit (key length).
The task is to search a string in a Trie using recursion.
Examples :
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
Approach :
Searching a key is similar to insertion operation, however, we only compare the characters and move down. The search can terminate due to the end of a string or lack of key in the trie. In the former case, if the endOfWord field of the last node is true, then the key exists in the trie. In the second case, the search terminates without examining all the characters of the key, since the key is not present in the trie.
Below is the implementation of the above approach :
CPP
// CPP program to search in a trie #include <bits/stdc++.h> 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 inert 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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.