Skip to content

Commit

Permalink
Merge pull request #623 from Vip2016-0/LeetCodeSol
Browse files Browse the repository at this point in the history
Implement_Trie
  • Loading branch information
gantavyamalviya authored Oct 5, 2022
2 parents aedc265 + 4653a73 commit aa6b500
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions CPP/Tries/implementTrie.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
class Node {
public:
char c;
Node* child[26];
bool isWord;

Node(char c) {
this -> c = c;
isWord = false;

for(int i = 0 ; i < 26 ; i++)
child[i] = NULL;
}
};

class Trie {
Node* root;
Node* getNode(string &s){
Node* curr = root;
for(auto &ch:s){
if(curr -> child[ch - 97] == NULL)
return NULL;
curr = curr -> child[ch - 97];
}

return curr;
}
public:
Trie() {
root = new Node('\0');
}

void insert(string word) {
Node* curr = root;

for(auto &ch:word){
if(curr -> child[ch - 97] == NULL)
curr -> child[ch - 97] = new Node(ch);
curr = curr -> child[ch - 97];
}

curr -> isWord = true;
}

bool search(string word) {
Node* reqNode = getNode(word);

return reqNode && reqNode -> isWord;
}

bool startsWith(string prefix) {
return getNode(prefix) != NULL;
}
};

0 comments on commit aa6b500

Please sign in to comment.