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

标签 python binary-search-tree traversal

我正在尝试使用字典和递归在 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
    }
}

视觉上看起来像这样:

Visual look of the above dictionary

这是我尝试使用递归将“数据”中每个列表的中间值(价格)增加和更新 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 - 更新二叉搜索树中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36395632/

相关文章:

python - git Push azure master azure fatal : Not a git repository (or any of the parent directories): . git

python - 为什么两个变量的值在 Python 中都会发生变化?

java - Java中遍历二叉搜索树时出现StackOverflowError

python - 实现中序遍历时出现NameError

c - 二叉搜索树中的搜索函数导致段错误

c - 依次遍历x个节点

python - 处理 4 - 线程 "AWT-EventQueue-0"中的异常

python - 列表中最小的 n 个数字

algorithm - 有多少种方法可以访问给定矩阵的所有点?

search - 如何在二叉树中找到给定深度的节点值的总和?