class Trie:
def __init__(self):
self.endword = False
self.children = [None]*26
def insert(self,word):
curr = self
for c in word:
if curr.children[ ord(c) - ord('a')] == None:
curr.children[ord(c) - ord('a')] = Trie()
curr = curr.children[ord(c) - ord('a')]
curr.endword = True
def print_trie(self,cur):
res = []
curr = self
if curr:
if curr.children:
for c in curr.children:
if c.endword == False:
for el in self.print_trie(c):
res.append(c + el)
else:
res.append('')
return res
def search(self,word):
curr =self
for c in word:
curr = curr.children[ord(c) - ord('a')]
if curr == None:
return False
if curr.endword:
return True
return False
def startsWith(self,prefix):
curr = self
for c in prefix:
curr = curr.children[ord(c)-ord('a')]
if curr == None:
return False
return True
main = Trie()
main.insert('apple')
main.insert('app')
main.insert('appetit')
main.insert('apples')
main.insert('tea')
main.print_trie(main)
Лог c за print_tr ie - вывести первый 'tr ie' (он же char), но моя реализация не имеет фактического значения.