二叉树问题---二叉搜索树查找、插入与删除的代码实现

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

查找

def Find(root, x):
    if not root:
        print("The number {} is not found".format(x))
        return None
    if root.val == x:
        print("True")
        return root
    elif x < root.val:
        return Find(root.left, x)
    elif x > root.val:
        return Find(root.right, x)

插入

def BSTinsert(root, x):
    if not root:
        root = TreeNode(x)
    elif root.val > x:
        root.left = BSTinsert(root.left, x)
    elif root.val < x:
        root.right = BSTinsert(root.right, x)
    return root

删除

def Delete(root, x):
    if not root:
        raise Exception("Element not found")
    elif root.val > x:
        root.left = Delete(root.left, x)
    elif root.val < x:
        root.right = Delete(root.right, x)
    elif root.left and root.right:
        TmpCell = FindMin(root.right)
        root.val = TmpCell.val
        root.right = Delete(root.right, root.val)
    else:
        if not root.left:
            root = root.right
        else:
            root = root.left
    return root

def FindMin(root):
    if not root:
        return None
    while root.left:
        root = root.left
    return root
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值