如何在Trie数据结构中打印所有单词

时间:2019-07-24 15:16:20

标签: python trie

我有Trie程序。我可以在Trie中搜索内容。我只想在添加内容后打印

class Trie:
    head = {}
    def printf(self):
         print (self.head)

    def add(self, word):
        cur = self.head
        for ch in word:
            if ch not in cur:
                cur[ch] = {}
            cur = cur[ch]
        cur['*'] = True

    def search(self, word):
        cur = self.head
        for ch in word:
            if ch not in cur:
                return False
            cur = cur[ch]

        if '*' in cur:
            return True
        else:
            return False

dictionary = Trie()
dictionary.add("hi")
dictionary.add("hello")
print(dictionary.search("hi"))
dictionary.printf()

除了此以外,还有其他更好的方法来打印内容

0 个答案:

没有答案