我有一个经典的树问题,找不到正确的解决方案。我在 python 字典中有一棵树,上面有树枝和叶子。我需要计算每个分支的所有子项(价格属性)的总和并将其存储在总和属性中。这是我的树(dict)的示例:
[
{
"id": 1,
"type": "group",
"name": "test-group 1",
"price": 0,
"sum": 0,
"children": [
{
"id": 2,
"type": "position",
"name": "test-inner 1",
"price": 5
},
{
"id": 3,
"type": "position",
"name": "test-inner 2",
"price": 10
}
]
},
{
"id": 4,
"type": "group",
"name": "test-group 2",
"sum": 0,
"children": [
{
"id": 5,
"type": "position",
"name": "test-inner 3",
"price": 5
},
{
"id": 6,
"type": "group",
"name": "test-group 3",
"sum": 0,
"children": [
{
"id": 7,
"type": "position",
"name": "test-inner 4",
"price": 5
},
{
"id": 8,
"type": "position",
"name": "test-inner 5",
"price": 10
}
]
}
]
}
]
我确定我需要递归并且已经找到解决方案来获得整个树的总和......但我也需要部分总和......
谢谢你的帮助!