python - Python - 提高树数据结构的效率
问题描述
我目前正在研究 python 中的 Tree 数据结构。目前,我正在尝试计算子树值,其中子树值等于给定节点子树中节点的最大值。例如对于给定的树:
A(5)
/ \
C(2) D(8)
|
B(10)
C 的子树值为 10,A 的子树值为 10,D 的子树值为 8,依此类推。我有以下代码用于将子树值向上传播(因为每个节点都有一个“subtree_value” element) 但我似乎无法改进我的算法。最初我使用递归,然后切换到嵌套循环,因为我对递归不是很有经验。但是,有什么方法可以在不需要嵌套循环的情况下做到这一点?
node = subtree_a
while node.parent != None: #iterates up the list until it reaches the root node
children = node.parent.children
for child in children:
if (child.subtree_value > node.parent.subtree_value): #updates subtree value of parent based on largest child key
node.parent.set_subtree_val(child.subtree_value)
node = node.parent
解决方案
推荐阅读
- python-3.x - 将 list() 函数应用于字典时会发生什么?
- mysql - 如何从 CURSOR 读取数据 - mysql 存储过程
- javascript - PhpStorm 无法 Ctrl+单击打开 JavaScript 工厂文件
- ios - 带有“上一个”和“下一个”键盘的工具栏
- javascript - 在 javascript 函数中传递字符串值
- c# - 这个 C# 语句的 VB.NET 版本中是否需要 unchecked 关键字?
- django - Django ModelForm 选择类型表单,其中 empty_label 未在 Django 中显示
- r - R 行之间的时间差
- php - 通过 Laravel 中的 Ajax() 从控制器传递查询对象以查看
- c++ - 为什么这种转换方法不编译?