删除二进制搜索树的方法什么都不做

时间:2017-03-23 04:35:26

标签: python binary-search-tree

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

def contains(root, value):
    if root is None:
        return False

    if value == root.data:
        return True

    if value < root.data:
        return contains(root.left, value)
    else:
        return contains(root.right, value)


def insert(root, value):
    if root is None:
        root = BinaryNode(value)
    else:
        if value > root.data:
            if root.right is None:
                root.right = BinaryNode(value)
            else:
                return insert(root.right, value)
        else:
            if root.left is None:
                root.left = BinaryNode(value)
            else:
                return insert(root.left, value)

def getMin(root):
    if root.left is None:
        return root.data
    return getMin(root.left)

def remove(root, value, parent = None):
    if root is None:
        return False
    elif value < root.data and root.left is not None:
        return remove(root.left, value, root)
    elif value > root.data and root.right is not None:
        return remove(root.right, value, root)
    else:
        if parent.left is not None and parent.right is None and \
           root.left is None and root.right is None:
               root = None
               parent.left = root



def inorder(root):
    if root is not None:
        inorder(root.left)
        print(root.data)
        inorder(root.right)


b =  BinaryNode(10)
insert(b, 8)
insert(b, 11)

remove(b,11)

inorder(b)

我正在为二元搜索树编写我的删除函数,我100%肯定它是正确的实现逻辑。我已经实现了删除叶节点的最基本情况。问题必须与python相关吗?当我尝试删除11时,它仍会在inorder遍历中打印出来。

1 个答案:

答案 0 :(得分:0)

删除节点的逻辑缺少必要的步骤。请在下面找到删除节点的代码:

{{1}}