Using unique_ptr c++. Code is self-explanatory for any-one familiar with TRIE.
This is not a tutorial for TRIE.
Useful Note :
unique_ptr.get() gives us the raw pointer which is needed to traverse the trie. As unique_ptr can not be shared or copied.
struct Node {
unordered_map<char, unique_ptr<Node>>Char2Node;
bool isword;
Node() {
Char2Node.clear();
isword = false;
}
};
class TRIE {
public:
unique_ptr<Node>root;
TRIE() {
root = make_unique<Node>();
}
void insertWord(const string& word) {
auto* curNode = root.get();
for(int i=0;i<word.size();i++) {
if(curNode->Char2Node.find(word[i]) == curNode->Char2Node.end()) {
curNode->Char2Node[word[i]] = make_unique<Node>();
}
curNode = curNode->Char2Node[word[i]].get();
}
curNode->isword = true;
}
bool searchWord(const string& word) {
auto* curNode = root.get();
for(int i=0;i<word.size();i++) {
if(curNode->Char2Node.find(word[i]) == curNode->Char2Node.end()) {
return false;
}
curNode = curNode->Char2Node[word[i]].get();
}
return curNode->isword;
}
};