[Python] What pointer comparison to use to test if parent node points to my node in the binary...

Discussão em 'Python' iniciado por Stack, Dezembro 6, 2024.

  1. Stack

    Stack Membro Participativo

    Edit: I thought self works like this in C++ and Java

    I am learning python and was trying to code the delete-node function for a binary tree. I was surprised - Why do '==', 'id' and 'is' pointer comparisons fail in this test of whether parent node points to my node in the binary tree?

    class Node:

    ...

    def delete(self, key):
    ....
    if node_to_delete.parent.left == self: // FAIL

    if node_to_delete.parent.left is self: // FAIL

    if id(node_to_delete.parent.left) is id(self): // FAIL


    In the debugger, I can see that the condition fails each time.

    But when I use one of the fields to compare, then it works. But this is wrong because it assumes 'key' is unique

    if node_to_delete.parent.left.key == key: // OK


    from

    def delete(self, key):
    (found, node_to_delete) = self.search(key)
    assert(found == True), f"key to be deleted:{key}- does not exist in the tree"
    # your code here
    if node_to_delete.left == None and node_to_delete.right == None:
    if node_to_delete.parent.left.key == key:
    node_to_delete.parent.left = None
    print('after deleting left child of parent, node_to_delete.parent.left ',node_to_delete.parent.left)
    if node_to_delete.parent.right.key == key:
    node_to_delete.parent.right = None
    ...

    Continue reading...

Compartilhe esta Página