-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathImplement Trie (Prefix Tree).py
51 lines (35 loc) · 1.28 KB
/
Implement Trie (Prefix Tree).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
39
40
41
42
43
44
45
46
47
48
49
class Node :
def __init__(self ):
self.child = {} # to hold the nodes.
self.end = False # to mark a node if it is the end node or not.
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word:str) -> None:
# time compl len(word)
sz = len(word)
temp = self.root # to hold the root node.
for ind , i in enumerate( word ) :
if i in temp.child.keys() : # if this curr char in the current node.
temp = temp.child[i] #another node.
else:
temp.child[i] = Node()
temp = temp.child[i]
if ind == sz - 1 :
temp.end = True
def search(self, word: str) -> bool:
temp = self.root
for i in word :
if i in temp.child.keys():
temp = temp.child[i]
else:
return 0
return temp.end == True
def startsWith(self, prefix: str) -> bool:
temp = self.root
for i in prefix :
if i in temp.child.keys():
temp = temp.child[i]
else:
return 0
return 1