Search code examples
pythonbinary-search-treetraversal

Updating data in a Binary Search Tree


I'm trying to update values in nodes in an implementation of a BST (Binary Search Tree) in Python using dictionaries and recursion. However, it's not working. Please enlighten me!

Here's my BST implementation using dictionaries in Python:

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
    }
}

which visually looks like this:

Visual look of the above dictionary

Here's my attempt to increase and update the middle value (price) of each list in 'data' by 10% using recursion yet it's not working for some reason I don't know of:

def IncreaseByTen(tree):
    if tree == None:
        return 0

    price = tree['data'][1]

    IncreaseByTen(tree['left'])
    price += (price * 0.1)
    IncreaseByTen(tree['right'])

Solution

  • Following line just change only the local variable price, not the list item:

    price += (price * 0.1)
    

    You need to assign the value back to the list item:

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

    or you can use *=:

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