字典树

class TrieNode:
    def __init__(self):
        self.nodes=dict()
        self.is_leaf=False

    def insert(self,word):#插入单词(字符列表)
        curr=self
        for char in word:#单词中的每个字母
            if char not in curr.nodes:
                curr.nodes[char]=TrieNode()
            curr=curr.nodes[char]

            if curr.is_leaf==True:#abcdef插到abc
                return False

        if len(curr.nodes)!=0:#abc插到abcdef
            return False

        curr.is_leaf=True
        return True

posted on 2020-03-01 19:45  HolaWorld  阅读(130)  评论(0编辑  收藏  举报

导航