-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.py
32 lines (28 loc) · 978 Bytes
/
trie.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end_of_word = True
def search(self, prefix):
node = self.root
for char in prefix:
if char not in node.children:
return []
node = node.children[char]
return self._words_with_prefix(node, prefix)
def _words_with_prefix(self, node, prefix):
words = []
if node.is_end_of_word:
words.append(prefix)
for char, child_node in node.children.items():
words.extend(self._words_with_prefix(child_node, prefix + char))
return words