更新二叉搜索树中的数据
Updating data in a Binary Search Tree
我正在尝试使用字典和递归在 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
}
}
视觉上看起来像这样:
这是我尝试使用递归将 'data' 中每个列表的中间值(价格)增加和更新 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
我正在尝试使用字典和递归在 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
}
}
视觉上看起来像这样:
这是我尝试使用递归将 'data' 中每个列表的中间值(价格)增加和更新 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