1

I want to delete a whole binary tree but the first root cannot be deleted and remains. How could I fix the code below so that I can delete the whole binary tree including the root node?

class binary_tree:
    def __init__(self, root) -> None:
        self.root = root
        self.left = None
        self.right = None

    def __str__(self):
        return '<%s, %d, %s>' % (self.left, self.root, self.right)


    def get_size(self):
        size = 1
        if self.left is not None:
            size += self.left.get_size()
        if self.right is not None:
            size += self.right.get_size()

        return size

def insert_left(root, data) -> None:
    if root.left is None:
        root.left = binary_tree(data)
    else:
        insert_left(root.left, data)

def insert_right(root, data) -> None:
    if root.right is None:
        root.right = binary_tree(data)
    else:
        insert_right(root.right, data)

def clear_tree(root):
    if root:
        root.left = clear_tree(root.left)
        root.right = clear_tree(root.right)
        print(f"deleting node left={root.left}, root={root.root},  right={root.right}")
        del root







if __name__ == '__main__':
    root = binary_tree(4)
    insert_left(root, 2)
    insert_right(root, 6)
    insert_left(root.left, 1)
    insert_right(root.left, 3)
    insert_left(root.right, 5)
    insert_right(root.right, 7)
    print(root)
    print(root.get_size())
    clear_tree(root)
    print(root.get_size())
    print(root)

    """
                4
               / \
              2   6
             / \ / \
            1  3 5  7


    """

I tried modifying the clear_tree method from

def clear_tree(root):
    if root:
        clear_tree(root.left)
        clear_tree(root.right)
        print(f"deleting node left={root.left}, root={root.root},  right={root.right}")
        del root

to

def clear_tree(root):
    if root:
        root.left = clear_tree(root.left)
        root.right = clear_tree(root.right)
        print(f"deleting node left={root.left}, root={root.root},  right={root.right}")
        del root

The former code did not delete any node in the tree, and the latter did except the root node. Thus the output looks like this;

<<<None, 1, None>, 2, <None, 3, None>>, 4, <<None, 5, None>, 6, <None, 7, None>>>
7
deleting node left=None, root=1,  right=None
deleting node left=None, root=3,  right=None
deleting node left=None, root=2,  right=None
deleting node left=None, root=5,  right=None
deleting node left=None, root=7,  right=None
deleting node left=None, root=6,  right=None
deleting node left=None, root=4,  right=None
1
<None, 4, None>

which I expect to look like;

<<<None, 1, None>, 2, <None, 3, None>>, 4, <<None, 5, None>, 6, <None, 7, None>>>
7
deleting node left=None, root=1,  right=None
deleting node left=None, root=3,  right=None
deleting node left=None, root=2,  right=None
deleting node left=None, root=5,  right=None
deleting node left=None, root=7,  right=None
deleting node left=None, root=6,  right=None
deleting node left=None, root=4,  right=None
0
<None, None, None> (<- I'm not sure about this. But the size should be 0)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
CS_study
  • 11
  • 1
  • `del root` is all you need to do. – tkausl Mar 11 '23 at 04:46
  • Welcome to Stack Overflow. Please read [ask] and take the [tour]. I removed the `dsa` tag from this question because it is **not** for "data structure and algorithms" questions - please read the tag descriptions when applying tags to a question. – Karl Knechtel Mar 11 '23 at 04:50
  • Anyway, the problem here isn't with understanding a data structure or algorithm; it's with understanding *how Python manages objects*, and with understanding *what `del` means in Python*. Python is a garbage-collected language; you cannot directly cause objects to cease to exist (because there are no "null pointers"), and do not need to do anything special to destroy them (you just need to stop having any references to them - see the linked duplicate). – Karl Knechtel Mar 11 '23 at 04:53
  • In your specific case: In `clear_tree`, doing `del root` makes **the local variable in that function** stop referring to any tree node. It does not get rid of the tree, because the top-level code has its own reference. It does not make sense in Python to try to implement functionality like this. But aside from that, think for a moment: if you get rid of all the nodes in the entire tree, including the `root` itself - then what do you expect `root.get_size()` to mean? – Karl Knechtel Mar 11 '23 at 04:55

0 Answers0