-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtrie.py
More file actions
37 lines (33 loc) · 944 Bytes
/
trie.py
File metadata and controls
37 lines (33 loc) · 944 Bytes
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
class TrieNode:
def __init__(self):
self.children = [None]*26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.parent = TrieNode()
def add(self, key):
if(len(key)==0):
self.parent.isEndOfWord = True
return
index = ord(key[0])-ord('a')
if(self.parent.children[index] == None):
self.parent.children[index] = Trie()
self.parent.children[index].add(key[1:])
def search(self, key):
if(len(key)==0):
print(self.parent.isEndOfWord)
return self.parent.isEndOfWord
index = ord(key[0])-ord('a')
if(self.parent.children[index] == None):
print(False)
return False
self.parent.children[index].search(key[1:])
def displayWords(self,word=''):
children = self.parent.children
for subTree in children:
if(subTree):
word+= chr(children.index(subTree) + ord('a'))
if(subTree.parent.isEndOfWord): print(word)
subTree.displayWords(word=word)
word=word[:-1]
word = ''