Skip to main content
 首页 » 编程设计

python之更新二叉搜索树中的数据

2025年04月02日22yjmyzz

我正在尝试使用字典和递归在 Python 中的 BST(二进制搜索树)实现中更新节点中的值。但是,它不起作用。请赐教!

这是我在 Python 中使用字典的 BST 实现:

tree = { 
    'right': None, 
    'data': [9124, 5.82, 5], 
    'left': { 
        'right': { 
            'right': None, 
            'data': [8298, 2.4, 6], 
            'left': None 
        }, 
        'data': [5549, 4.76, 5], 
        'left': None 
    } 
} 

视觉上看起来像这样:

这是我尝试使用递归将“数据”中每个列表的中间值(价格)增加和更新 10% 但由于某种我不知道的原因它不起作用:

def IncreaseByTen(tree): 
    if tree == None: 
        return 0 
 
    price = tree['data'][1] 
 
    IncreaseByTen(tree['left']) 
    price += (price * 0.1) 
    IncreaseByTen(tree['right']) 

请您参考如下方法:

下一行只改变局部变量price,而不是列表项:

price += (price * 0.1) 

您需要将值分配回列表项:

price = tree['data'][1] 
... 
price += (price * 0.1) 
tree['data'][1] = price  # <---- 

或者你可以使用*=:

tree['data'][1] *= 1.1