|
| 1 | +#include<iostream> |
| 2 | +#include<string> |
| 3 | +using namespace std; |
| 4 | +class TrieNode{ |
| 5 | + public: |
| 6 | + char data; |
| 7 | + TrieNode **children; |
| 8 | + bool isTerminal; |
| 9 | + TrieNode(char data){ |
| 10 | + this->data=data; |
| 11 | + children=new TrieNode*[26]; |
| 12 | + for(int i=0;i<26;i++){ |
| 13 | + children[i]=NULL; |
| 14 | + } |
| 15 | + isTerminal=false; |
| 16 | + } |
| 17 | +}; |
| 18 | +class Trie{ |
| 19 | + TrieNode* root; |
| 20 | + public: |
| 21 | + Trie(){ |
| 22 | + root=new TrieNode('0円'); |
| 23 | + } |
| 24 | + void insertWord(TrieNode* root,string word){ |
| 25 | + //base case |
| 26 | + if(word.size()==0){ |
| 27 | + root->isTerminal=true; |
| 28 | + return; |
| 29 | + } |
| 30 | + //small calculation |
| 31 | + int index=word[0]-'a'; |
| 32 | + TrieNode* child; |
| 33 | + if(root->children[index]!=NULL){ |
| 34 | + child=root->children[index]; |
| 35 | + } |
| 36 | + else{ |
| 37 | + child=new TrieNode(word[0]); |
| 38 | + root->children[index]=child; |
| 39 | + } |
| 40 | + //recursive call |
| 41 | + insertWord(child,word.substr(1)); |
| 42 | + } |
| 43 | + //For user |
| 44 | + void insertWord(string word){ |
| 45 | + insertWord(root,word); |
| 46 | + } |
| 47 | + bool search(TrieNode* root,string word){ |
| 48 | + if(word.length()==0){ |
| 49 | + return root->isTerminal; |
| 50 | + } |
| 51 | + int index=word[0]-'a'; |
| 52 | + TrieNode* child; |
| 53 | + if(root->children[index]!=NULL){ |
| 54 | + child=root->children[index]; |
| 55 | + } |
| 56 | + else{ |
| 57 | + return false; |
| 58 | + } |
| 59 | + return search(child,word.substr(1)); |
| 60 | + } |
| 61 | + bool search(string word){ |
| 62 | + return search(root,word); |
| 63 | + } |
| 64 | + void removeWord(TrieNode* root,string word){ |
| 65 | + //base case |
| 66 | + if(word.size()==0){ |
| 67 | + root->isTerminal=false; |
| 68 | + return; |
| 69 | + } |
| 70 | + //small calculation |
| 71 | + TrieNode* child; |
| 72 | + int index=word[0]-'a'; |
| 73 | + if(root->children[index]!=NULL){ |
| 74 | + child=root->children[index]; |
| 75 | + } |
| 76 | + else{ |
| 77 | + //word not found |
| 78 | + return; |
| 79 | + } |
| 80 | + removeWord(child,word.substr(1)); |
| 81 | + //remove child node if it is useless |
| 82 | + if(child->isTerminal==false){ |
| 83 | + for(int i=0;i<26;i++){ |
| 84 | + if(child->children[i]!=NULL){ |
| 85 | + return; |
| 86 | + } |
| 87 | + } |
| 88 | + delete child; |
| 89 | + root->children[index]=NULL; |
| 90 | + } |
| 91 | + } |
| 92 | + void removeWord(string word){ |
| 93 | + removeWord(root,word); |
| 94 | + } |
| 95 | +}; |
| 96 | +int main(){ |
| 97 | + Trie t; |
| 98 | + t.insertWord("and"); |
| 99 | + t.insertWord("are"); |
| 100 | + t.insertWord("dot"); |
| 101 | + cout<<t.search("and")<<endl; |
| 102 | + t.removeWord("and"); |
| 103 | + cout<<t.search("and")<<endl; |
| 104 | +} |
0 commit comments