I've implemented a basic Trie that is supposed to work only with lowercase English letters.
class TrieNode {
public:
array<shared_ptr<TrieNode>, 26> children;
bool isWord;
TrieNode(bool _isWord = false) : isWord{_isWord} {
}
};
class Trie {
public:
Trie() : root{make_shared<TrieNode>(TrieNode())} {
}
void insert(const string& word) {
auto p = root;
for (const auto& ch : word) {
const auto idx = ch - 'a';
if (p->children[idx] == nullptr) {
p->children[idx] = make_shared<TrieNode>(TrieNode());
}
p = p->children[idx];
}
p->isWord = true;
}
bool search(const string& word, bool prefix = false) {
auto p = root;
for (const auto& ch : word) {
const auto idx = ch - 'a';
if (p->children[idx] == nullptr) {
return false;
}
p = p->children[idx];
}
if (prefix) {
return true;
}
return p->isWord;
}
bool startsWith(const string& prefix) {
return search(prefix, true);
}
private:
shared_ptr<TrieNode> root;
};
Is the use of shared_ptr
appropriate here? Could I get more efficiency from this code?