在python中通过dict实现trie数据结构

问题描述

在python中从dict实现trie,首先我试着理解别人的代码

class Trie:
    def __init__(self):
        self.t = {}
    def insert(self,word: str) -> None:
        node = self.t
        for c in word:
            if c not in node:
                node[c] = {}
            node = node[c]
            print(node)
        node['-'] = True

调用函数“插入”

d = Trie()
d.insert("word")
d.insert("welcome")
d.insert("what")

结果是

{}
{}
{}
{}
{'o': {'r': {'d': {'-': True}}}}
{}
{}
{}
{}
{}
{}
{'o': {'r': {'d': {'-': True}}},'e': {'l': {'c': {'o': {'m': {'e': {'-': True}}}}}}}
{}
{}
{}

我对结果感到困惑,尤其是非空的结果。代码 node = node[c] 如何获得这样的结果?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)