Search code examples
pythonbinary-search-treereference-counting

Do we need to use root = None during in the function? (python BST, reference counting)


I am practicing deleting node in BST and came across the following code.

def deleteNode(root, key):

    if root is None:
        return root

    if key < root.key:
        root.left = deleteNode(root.left, key)

    elif(key > root.key):
        root.right = deleteNode(root.right, key)

    else:
        if root.left is None:
            temp = root.right
            root = None
            return temp

        elif root.right is None:
            temp = root.left
            root = None
            return temp

        temp = minValueNode(root.right)
        root.key = temp.key
        root.right = deleteNode(root.right, temp.key)

    return root

My question is do we need the line of root = None? According to reference counting, I feel root will be automatically destroyed as the only reference like parent.child is detached. Any explanation is greatly appreciated.


Solution

  • Given that root = None is immediately followed by return temp, it is just (re-)binding a local variable that is immediately discarded again and has no effect whatsoever.

    In the given code, the lines root = None can be removed without changing the result of running the code.

    Presumably the code was translated too literally from a different language where assigning to a variable changes the contents of a memory location.

    But in Python, the assignment operator = just binds a new name1 to an already existing object (in this case it gives the name root to the object None) and does not change the object or any other object in memory.


    1 at least with "simple names" on the left-hand side, it is a bit more complicated when assigning to something like a[i].