data-structures-algorithms-python icon indicating copy to clipboard operation
data-structures-algorithms-python copied to clipboard

delete function in BST not working while deleting first element if its the lowest

Open snehA5e8a opened this issue 1 year ago • 1 comments

https://github.com/codebasics/data-structures-algorithms-python/blob/master/data_structures/9_Binary_Tree_2/binary_tree_part_2.py image

snehA5e8a avatar Jul 23 '24 09:07 snehA5e8a

Use the following code, it covers all the cases (root deletion, as well as if there's only one element in the tree, i.e. root), if there are only left subtree to the root and if there is only right subtree to the root: HOPE THAT HELPS! :) :)

def delete_node(self, value):
    if value < self.data:
        if self.left:
            self.left = self.left.delete_node(value)

    elif value > self.data:
        if self.right:
            self.right = self.right.delete_node(value)

    else:
        if self.left is None and self.right is None:
            self.data = None
            return None
        
        else:  
            if self.right:
                min_val = self.right.find_min()
                self.data = min_val
                self.right = self.right.delete_node(min_val)

            elif self.left:
                max_val = self.left.find_max()
                self.data = max_val
                self.left = self.left.delete_node(max_val)

    return self

RohanMehraa avatar May 05 '25 16:05 RohanMehraa