You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python树后序遍历实现:叶子节点向父节点累加奖励分逻辑

实现叶子节点向父节点累加奖励分的逻辑

核心思路是后序遍历树结构,先计算所有子节点的总分(含子节点自身分数及子节点获得的奖励),再基于子节点总分计算父节点的奖励分,这样能保证父节点拿到的是子节点最终的总分数据。

实现步骤

  • 遍历树时采用后序顺序,确保子节点先于父节点完成计算
  • 每个节点的总分 = 自身基础分数 + 所有子节点总分之和 × 10%
  • 为节点新增total_points属性存储最终总分,保留原points属性作为基础分

完整代码实现

from bigtree import nested_dict_to_tree, print_tree, postorder_iter

path_dict = {
   "name": "a",
   "points": 100,
   "children": [
      {
         "name": "b",
         "points": 50,
         "children": [
            {"name": "d", "points": 40},
            {"name": "e", "points": 20},
         ],
      },
      {"name": "c", "points": 60},
   ],
}
root = nested_dict_to_tree(path_dict)

# 遍历所有节点,计算总分
for node in postorder_iter(root):
    # 叶子节点的子节点总分和为0,总分等于自身基础分
    child_total_sum = sum(child.total_points for child in node.children)
    node.total_points = node.points + 0.1 * child_total_sum

# 打印树结构及基础分、总分
print_tree(root, attr_list=["points", "total_points"])

输出结果验证

运行代码后会输出:

a [points=100, total_points=111.6]
├── b [points=50, total_points=56.0]
│   ├── d [points=40, total_points=40.0]
│   └── e [points=20, total_points=20.0]
└── c [points=60, total_points=60.0]

完全符合需求:

  • 节点d、e是叶子节点,总分等于自身基础分
  • 节点b的总分:50 + (40+20)×10% = 56
  • 节点a的总分:100 + (56+60)×10% = 111.6

内容的提问来源于stack exchange,提问作者varun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 00:50:23