简单Trie树

有一个txt文件,每一行是一个单词,构建一棵字典树

txt文件:

简单Trie树_第1张图片

简陋的实现,未优化:

class node:
    def __init__(self, eachChar):
        self.val = eachChar
        self.count = 0
        self.nextNode = dict()


rootNode = node('#')
for line in open('words.txt'):
    tmpList = list(line.strip())
    curNode = rootNode
    newWord = 0
    for i in range(len(tmpList)):
        if tmpList[i] in curNode.nextNode:
            curNode.nextNode[tmpList[i]].count += 1
            curNode = curNode.nextNode[tmpList[i]]
        else:
            newWord = 1
            newNode = node(tmpList[i])
            newNode.count = 1
            curNode.nextNode[tmpList[i]] = newNode
            curNode = curNode.nextNode[tmpList[i]]
    if not newWord:
        print("Word already exsit:", line.strip())


# 层次遍历
queueList = []
nodeList = []
nodeList.append(rootNode)
while nodeList:
    queueList = []
    for i in range(len(nodeList)):
        tmpNode = nodeList.pop(0)
        for key, value in tmpNode.nextNode.items():
            queueList.append(key)
            nodeList.append(value)
    if queueList:
        print(queueList)


# 查找
while 1:
    word = input("input the word:")
    tmpList = list(word.strip())
    curNode = rootNode
    newWord = 0
    for i in range(len(tmpList)):
        if tmpList[i] in curNode.nextNode:
            curNode = curNode.nextNode[tmpList[i]]
        else:
            print(word, 0)
            break
    if curNode.val == tmpList[-1]:
        print(word, curNode.count)

运行:

简单Trie树_第2张图片

你可能感兴趣的:(算法学习)