Python中的非二叉树数据结构

时间:2020-03-07 15:46:39

标签: python python-3.x data-structures tree trie

example

有人对我如何重新创建它有想法吗?

最终目标是遍历树并计算每个端点。在这种情况下,3因为1、3、2都是端点。

1 个答案:

答案 0 :(得分:1)

如果您不想使用简单的列表,则可以构建一个基本类。像这样:

class NonBinTree:

    def __init__(self, val):
        self.val = val
        self.nodes = []

    def add_node(self, val):
        self.nodes.append(NonBinTree(val))

    def __repr__(self):
        return f"NonBinTree({self.val}): {self.nodes}"


a = NonBinTree(0)
a.add_node(1)
a.add_node(3)
a.add_node(4)
a.nodes[2].add_node(2)

print(a)

然后添加所需的其他任何方法。