Python全系列 教程
3567个小节阅读:5930.5k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
先在二叉树中查找到目标节点,再将其删除
与插入节点类似,我们需要保证在删除操作完成后,二叉搜索树的"左子树 < 根节点 < 右子树"的性质仍然满足
因此,我们根据目标节点的子节点数量,3种情况,执行对应的删除节点操作
xxxxxxxxxx
def delete(self,num):
''' 删除节点 '''
# 判断树是否为空
if self.root is None:
return
# 查找删除的节点
cur,pre = self.root,None
# 遍历查找
while cur is not None:
# 判断值的大小
if cur.item == num:
break
pre = cur
# 判断值的大小,决定遍历的方向
if cur.item < num:
cur = cur.right
else:
cur = cur.left
# 判断是否找到了要删除的节点
if cur is None:
return
# 判断当前节点的子节点情况
if cur.left is None or cur.right is None:
# 有0个或这1个子节点
# 获取子节点
child = cur.left or cur.right
if cur == self.root:
self.root = child
else:
if pre.left == cur:
pre.left = child
else:
pre.right = child
else:
# 2个子节点 中序遍历获取后继节点 ,替换要删除的节点
temp = cur.right
while temp.left is not None:
temp = temp.left
self.delete(temp.item)
# 替换节点
cur.item = temp.item