class TrieNode:
def __init__(self):
self.children=[None]*26
self.isEndOfWord=False
class Trie:
def __init__(self):
self.root=self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self,ch):
return ord(ch)-ord('a')
def search(self,key):
pCrawl=self.root
length=len(key)
for level in range(length):
index=self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl=pCrawl.children[index]
return pCrawl.isEndOfWord
def insert(self,key):
pCrawl=self.root
length=len(key)
for level in range(length):
index=self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index]=self.getNode()
pCrawl=pCrawl.children[index]
pCrawl.isEndOfWord=True
def delete(self,key):
queue=[]
pCrawl=self.root
prev=self.root
length=len(key)
for level in range(length):
index=self._charToIndex(key[level])
if not pCrawl.children[index]:
return
if pCrawl.isEndOfWord:
queue.append([pCrawl,level])
pCrawl=pCrawl.children[index]
if pCrawl.isEndOfWord == False:
return
flag=False
for i in range(26):
if pCrawl.children[index]:
flag=True
if flag:
pCrawl.isEndOfWord==False
return
if len(queue)==0:
index=self._charToIndex(key[0])
self.root.children[index]=None
return
pCrawl,level=queue.pop()
index=self._charToIndex(key[level])
pCrawl.children[index]=None
def haschild(self,node):
for i in range(26):
if node.children[i]:
return True
return False
def displayUtil(self,visited,node,str):
index=0
while index<26:
if node.children[index]:
str+=chr(97+index)
if node.children[index].isEndOfWord == False:
self.displayUtil(visited,node.children[index],str)
str=str[0 : (len(str)-1)]
else:
if str not in visited:
visited.append(str)
if self.haschild(node.children[index]):
self.displayUtil(visited,node.children[index],str)
str=str[0 : (len(str)-1)]
index+=1
def display(self):
visited=[]
str=''
self.displayUtil(visited,self.root,str)
print("Content of Trie:")
for i in range(len(visited)):
print(visited[i])
keys = ["the","a","there","bye","any",
"by","their","answer"]
output = ["Not present in trie","Present in trie"]
t=Trie()
for key in keys:
t.insert(key)
t.display()