建强
用Python写了一个简单的程序:
# 前缀树构造与查询
# 前缀树节点
class PrefixNode:
def __init__(self, letter):
self.letter = letter # 每个节点中存储一个单词的字母
self.childnode = {} # 子节点用字典存储
self.isend = False # isend表示单词是否结束
def addchild(self, child):
self.childnode[child.letter] = child
# 寻找字母为letter的子节点
def findchild(self, letter):
return self.childnode.get(letter)
# 前缀树
class PrefixTree:
def __init__(self):
self.root = PrefixNode('#') # 用#号代表根节点
# 向字典树中加入一个单词
def addWord(self, word):
p = self.root
for w in word:
childnode = p.findchild(w)
if childnode is None:
# 前缀树中没有找到对应的字母,则重新构造一个新的子节点
childnode = PrefixNode(w)
p.addchild(childnode)
p = childnode
p.isend = True
# 在字典树中查找一个单词
def searchWord(self, word):
p = self.root
for w in word:
childnode = p.findchild(w)
if childnode is None:
# 前缀树中没有找到对应的字母,则直接返回False
return False
p = childnode
return p.isend
# 主程序
def main():
# 构造字典树
dict_tree = PrefixTree()
# 向字典树中加入一些单词
for word in ['beautiful','student','computer','desk','table','design','book','bookshelf']:
dict_tree.addWord(word)
print('prefix tree is maded')
# 在字典树中查找单词
for word in ['beau', 'book','student', 'conputer', 'bookshelf', 'desks']:
if dict_tree.searchWord(word):
print('"{}" was founded.'.format(word))
else:
print('"{}" was not founded.'.format(word))
if __name__ == '__main__':
main()