delete node in binary search tree python

雨燕双飞 提交于 2019-12-05 11:25:14
def delete(self, key):
    """ delete the node with the given key and return the 
    root node of the tree """

    if self.key == key:
        # found the node we need to delete

        if self.right and self.left: 

            # get the successor node and its parent 
            [psucc, succ] = self.right._findMin(self)

            # splice out the successor
            # (we need the parent to do this) 

            if psucc.left == succ:
                psucc.left = succ.right
            else:
                psucc.right = succ.right

            # reset the left and right children of the successor

            succ.left = self.left
            succ.right = self.right

            return succ                

        else:
            # "easier" case
            if self.left:
                return self.left    # promote the left subtree
            else:
                return self.right   # promote the right subtree 
    else:
        if self.key > key:          # key should be in the left subtree
            if self.left:
                self.left = self.left.delete(key)
            # else the key is not in the tree 

        else:                       # key should be in the right subtree
            if self.right:
                self.right = self.right.delete(key)

    return self

def _findMin(self, parent):
    """ return the minimum node in the current tree and its parent """

    # we use an ugly trick: the parent node is passed in as an argument
    # so that eventually when the leftmost child is reached, the 
    # call can return both the parent to the successor and the successor

    if self.left:
        return self.left._findMin(self)
    else:
        return [parent, self]

This might help. For complete code and better understanding go to For code Binary search Tree in Python

For explanation Notes on BST in Python As per my knowledge its working fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!