Search code examples
pythontreebinary-treebinary-search-tree

How to delete a node from a tree. I am trying to delete the node from the function but still it is getting print even after deleting


I am deleting the node from delete function and when print it within function it shows its None

But when done out of the function it prints the value please correct me, tell me what's wrong in this code

Note:Class Node has only init method and other function are outside the class

class Node:

    def __init__(self,data):
        self.data = data
        self.left = None
        self.right = None 

def printit(obj):

    if obj:
        printit(obj.left)
        print(obj.data)
        printit(obj.right)
    return

def insert(obj, data):

    if obj.left == None:
        obj.left = Node(data)
        return
    
    if obj.right == None:
        obj.right = Node(data)
        return
    
    insert(obj.left, data)
    

def delet(obj):

    if obj.left == None:
        obj= None
        return
    delet(obj.left)     
f = Node(50)

f.left = Node(15)

f.right = Node(75)

delet(f)

printit(f)

Solution

  • obj= None only affects the value of that name. It doesn't affect anything related to the previous value of obj.

    If you want to change the tree structure, you'll have to assign to an attribute, not to a variable name.

    Think also what happens when the very last node is deleted: then the main program should get its f set to None. This can only happen if you return something that the caller can assign back to their own variable.

    For instance:

    def delet(obj):
        if obj.right is not None:
            obj.right = delet(obj.right)
        elif obj.left is not None:
            obj.left = delet(obj.left)
        else:
            return None
        return obj
    

    You should then also use the returned value in the main code:

    f = Node(50)
    f.left = Node(15)
    f.right = Node(75)
    printit(f)
    print("---")
    
    f = delet(f)
    printit(f)
    print("---")
    
    f = delet(f)
    printit(f)
    print("---")
    
    f = delet(f)
    printit(f)
    print("---")