A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie()
Initializes the trie object.void insert(String word)
Inserts the string word into the trie.boolean search(String word)
Returnstrue
if the stringword
is in the trie (i.e., was inserted before), andfalse
otherwise.boolean startsWith(String prefix)
Returnstrue
if there is a previously inserted stringword
that has the prefixprefix
, andfalse
otherwise.
Example :
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]
Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // return True
trie.search("app"); // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app"); // return True
Approach:
C++
#include <bits/stdc++.h>using namespace std;struct Node{char val = '\0';struct Node *child[26];bool isword = false;};Node *root = new Node();//funtion to insert word//into the trievoid insert(string word){Node *node = root;for (int i = 0; i < word.size(); i++){char c = word[i];int index = c - 'a';if (node->child[index]){node = node->child[index];continue;}node->child[index] = new Node();node->child[index]->val = c;node = node->child[index];}node->isword = true;}//check if word is present in the//triebool search(string word){struct Node *node = root;for (int i = 0; i < word.size(); i++){char c = word[i];int index = c - 'a';if (!node->child[index])return false;node = node->child[index];}if (node->isword)return true;return false;}bool startsWith(string prefix){Node *node = root;for (int i = 0; i < prefix.size(); i++){char c = prefix[i];int index = c - 'a';if (!node->child[index])return false;node = node->child[index];}return true;}int main(){cout << "[";insert("apple");if (search("apple"))cout << "true, ";elsecout << "false, ";if (search("app"))cout << "true, ";elsecout << "false, ";if (startsWith("app"))cout << "true, ";elsecout << "false, ";insert("app");if (search("app"))cout << "true";elsecout << "false";cout << "]";return 0;}