Trie Template
class TrieNode(object):
def __init__(self):
self.children = {}
self.isWord = False
class Trie(object):
def __init__(self):
self.root = TrieNode()
def addWord(self,word):
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.isWord = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
for w in word:
if w not in node.children:
return False
node = node.children[w]
return node.isWord
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for w in prefix:
if w not in node.children:
return False
node = node.children[w]
return True
Last updated
Was this helpful?