lecture 79 :Trie & its Implementation code} is missing
Opened this issue · 1 comments
divyanshu-vashu commented
can anyone add code for lecture 79 :Trie & its Implementation code is missing
aryamanbro commented
can anyone add code for lecture 79 :Trie & its Implementation code is missing
class TrieNode{
public:
char data;
TrieNode* children[26];
bool isterminal;
/** Initialize your data structure here. */
TrieNode(char data) {
this->data=data;
for (int i = 0; i < 26; i++) {
children[i] = NULL;
}
isterminal=false;
}
};
class Trie {
public:
TrieNode *root;
Trie(){
root= new TrieNode('\0');
}
/** Inserts a word into the trie. */
void insert(string word) {
insertword(root,word);
}
void insertword(TrieNode* root,string word){
if(word.length()==0){
root->isterminal=true;
return;
}
int index=word[0]-'a';
TrieNode* child;
if(root->children[index]!=NULL){
child=root->children[index];
}
else{
child=new TrieNode(word[0]);
root->children[index]=child;
}
insertword(child,word.substr(1));
}
/** Returns if the word is in the trie. */
bool search(string word){
return searchword(root,word);
}
bool searchword(TrieNode* root,string word){
if(word.length()==0){
return root->isterminal;
}
int index=word[0]-'a';
TrieNode* child;
if(root->children[index]!=NULL){
child=root->children[index];
}
else{
return false;
}
return searchword(child,word.substr(1));
}
bool start(TrieNode* root, string word){
if(word.length()==0){
return true;
}
int index=word[0]-'a';
TrieNode* child;
if(root->children[index]!=NULL){
child=root->children[index];
}
else{
return false;
}
return start(child,word.substr(1));
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return start(root,prefix);
}
};