Skip to content

Instantly share code, notes, and snippets.

@jeb2239
Forked from nhudinhtuan/trie.py
Last active January 8, 2021 02:24
Show Gist options
  • Save jeb2239/5f1d342ba117bb93712445674aec0d8d to your computer and use it in GitHub Desktop.
Save jeb2239/5f1d342ba117bb93712445674aec0d8d to your computer and use it in GitHub Desktop.
Trie Data Structure
class TrieNode(object):
def __init__(self):
self.children = {}
self.is_word = False # mark the end of a word
class Trie(object):
def __init__(self):
# initialize the root node
self.root = TrieNode()
def add(self, word):
# add a new word to the trie
current = self.root
for c in word:
if c not in current.children:
# create new node if the character is not in children
current.children[c] = TrieNode()
current = current.children[c]
# mark the end of word
current.is_word = True
def search(self, word):
# return True if the word is in the trie
current = self.root
for c in word:
if c not in current.children:
return False
current = current.children[c]
return current.is_word
def search_prefix(self, prefix):
# return True if the prefix is in the trie
current = self.root
for c in prefix:
if c not in current.children:
return False
current = current.children[c]
# we don't need a completed word for prefix
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment