python - Python 中的非二叉树数据结构

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

example

有谁知道我如何重新创建这个:

最终目标是遍历树并计算每个端点。在本例中为 3,因为 1、3、2 都是端点。

最佳答案

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

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)

然后添加您想要的任何其他方法。

关于python - Python 中的非二叉树数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60579330/

相关文章:

python - 使用数组输入的 Sympy Lambdify

python - 列的高效过滤

python - Pandas - 基于另一列为基于另一列的组创建列增量

python - 重置 lru_cache 中的缓存

data-structures - 用于估计降阶有序二元决策图效率的启发式方法?

python - 用于字符串查找的集合与正则表达式,哪个更具可扩展性?

python - 在 Python 2.x 中打印嵌套字典中的值

python - 输入后的字符串验证或 Python 中的 raw_input

arrays - 压缩数组返回为 <zip object at 0x02B6F198>

c++ - 有人可以解释一下这行代码吗