-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrie.py
39 lines (34 loc) · 1.08 KB
/
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
33
34
35
36
37
38
class Trie:
def __init__(self, is_end=False):
self.children = {}
self.is_end = is_end
def insert(self, s):
node = self
for ch in s:
if ch not in node.children:
node.children[ch] = Trie()
node = node.children[ch]
node.is_end = True
def build(self, words):
for word in words:
self.insert(word)
return self
def search(self, s):
node = self
for ch in s:
if ch not in node.children:
return None
node = node.children[ch]
return node if node.is_end else None
def delete(self, s):
def rec(node, s, i):
if i == len(s):
node.is_end = False
return len(node.children) == 0
else:
next_deletion = rec(node.children[s[i]], s, i+1)
if next_deletion:
del node.children[s[i]]
return next_deletion and not node.is_end and len(node.children) == 0
if self.search(s):
rec(self, s, 0)