LeetCode Solutions
208. Implement Trie (Prefix Tree)
Time: Space:
struct TrieNode {
vector<shared_ptr<TrieNode>> children;
bool isWord = false;
TrieNode() : children(26) {}
};
class Trie {
public:
void insert(const string& word) {
shared_ptr<TrieNode> node = root;
for (const char c : word) {
const int i = c - 'a';
if (node->children[i] == nullptr)
node->children[i] = make_shared<TrieNode>();
node = node->children[i];
}
node->isWord = true;
}
bool search(const string& word) {
shared_ptr<TrieNode> node = find(word);
return node && node->isWord;
}
bool startsWith(const string& prefix) {
return find(prefix) != nullptr;
}
private:
shared_ptr<TrieNode> root = make_shared<TrieNode>();
shared_ptr<TrieNode> find(const string& prefix) {
shared_ptr<TrieNode> node = root;
for (const char c : prefix) {
const int i = c - 'a';
if (node->children[i] == nullptr)
return nullptr;
node = node->children[i];
}
return node;
}
};
class TrieNode {
public TrieNode[] children = new TrieNode[26];
public boolean isWord = false;
}
class Trie {
public void insert(String word) {
TrieNode node = root;
for (final char c : word.toCharArray()) {
final int i = c - 'a';
if (node.children[i] == null)
node.children[i] = new TrieNode();
node = node.children[i];
}
node.isWord = true;
}
public boolean search(String word) {
TrieNode node = find(word);
return node != null && node.isWord;
}
public boolean startsWith(String prefix) {
return find(prefix) != null;
}
private TrieNode root = new TrieNode();
private TrieNode find(String prefix) {
TrieNode node = root;
for (final char c : prefix.toCharArray()) {
final int i = c - 'a';
if (node.children[i] == null)
return null;
node = node.children[i];
}
return node;
}
}
class TrieNode:
def __init__(self):
self.children: Dict[str, TrieNode] = defaultdict(TrieNode)
self.isWord = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node: TrieNode = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.isWord = True
def search(self, word: str) -> bool:
node: TrieNode = self._find(word)
return node and node.isWord
def startsWith(self, prefix: str) -> bool:
return self._find(prefix)
def _find(self, prefix: str) -> Optional[TrieNode]:
node: TrieNode = self.root
for c in prefix:
if c not in node.children:
return None
node = node.children[c]
return node