delete function in BST not working while deleting first element if its the lowest · Issue #94 · codebasics/data-structures-algorithms-python · GitHub
Skip to content

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

Open

Activity

  1. RohanMehraa commented on May 5, 2025

    @RohanMehraa

    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
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions