classNode:def__init__(self, c=''):
self.is_end =False
self.subNode =[]
self.c = c
definsert(self, word:str):
flag =Falsenext=Nonefor sb in self.subNode:if word[0]== sb.c[0]:
flag =Truenext= sb
breakifnot flag:next= Node(word[0])
self.subNode.append(next)iflen(word[1:]):next.insert(word[1:])else:next.is_end =Truedefsearch(self, word:str)->bool:for n in self.subNode:if word[0]== n.c[0]:if word[1:]:return n.search(word[1:])else:return n.is_end
returnFalsedefstartsWith(self, word:str)->bool:for n in self.subNode:if word[0]== n.c[0]:if word[1:]:return n.startsWith(word[1:])else:returnTruereturnFalse
classTrie:def__init__(self):"""
Initialize your data structure here.
"""
self.root = Node()definsert(self, word:str)->None:"""
Inserts a word into the trie.
"""
self.root.insert(word)defsearch(self, word:str)->bool:"""
Returns if the word is in the trie.
"""return self.root.search(word)defstartsWith(self, prefix:str)->bool:"""
Returns if there is any word in the trie that starts with the given prefix.
"""return self.root.startsWith(prefix)# 分层打印defprint_tree(self, node):
vec =[]
vec.append(node)
i =0while i <len(vec):
j =len(vec)
cur_level =[]while i < j:for n in vec[i].subNode:
vec.append(n)
cur_level.append(n.c)
i +=1print(cur_level)