其中bst为算法10中的代码
from bst import Bitree,bst
class AVLNode:
def __init__(self, data): # 建立二叉树
self.data = data
self.lchild = None
self.rchild = None
self.parent = None
self.bf=0
class AVLTree(bst):
def __init__.
256/256
文章标签:
*
分类专栏:
新建分类专栏
文章类型:
申请原创将启用 Creative Commons 版权模板,如果不是原创文章,请选择转载或翻译。 原创文章默认开启打赏, 打赏管理
发布形式:
所有用户将均可访问和阅读,优质文章将会获得更高的推荐曝光
内容等级:
*
共 2237 字
发布文章
topSpInfo
Python
# 开发时间: 15:23
from bst import Bitree,bst
class AVLNode:
def __init__(self, data): # 建立二叉树
self.data = data
self.lchild = None
self.rchild = None
self.parent = None
self.bf=0
class AVLTree(bst):
def __init__(self,li):
bst.__init__(self,li)
def rotate_left(self,p,c):
s2=c.lchild
p.rchild=s2
if s2:
s2.parent=p
c.lchild=p
p.parent = c
p.bf=0
c.bf=0
return c
def rotate_right(self,p,c):
s2=c.rchild
p.lchild=s2
if s2:
s2.parent=p
c.rchild=p
p.parent=c
p.bf=0
c.bf=0
return c
def rotate_right_left(self,p,c):
g=c.lchild
s3=g.rchild
c.lchild=s3
if s3:
s3.parent=c
g.rchild=c
c.parent=g
s2=g.lchild
p.rchild=s2
if s2:
s2.parent=p
g.lchild=p
p.parent = g
#更新bf
if g.bf>0:
p.bf=-1
c.bf=0
elif g.bf<0:
p.bf=0
c.bf=1
else:
p.bf=0
c.bf=0
g.bf=0
return g
def rotate_left_right(self,p,c):
g=c.rchild
s2=g.lchild
c.rchild=s2
if s2:
s2.parent=c
g.lchild = c
c.parent=g
s3=g.rchild
p.lchild=s3
if s3:
s3.parent=p
g.rchild=p
p.parent=g
#更新bf
if g.bf<0:
p.bf=1
c.bf=0
elif g.bf>0:
p.bf=0
c.bf=-1
else:
p.bf=0
c.bf=0
g.bf=0
return g
def insert_no_rec(self, val): # 非递归插入
#1.和BST一样,插入元素
p = self.root # 创建指针
if not p: # 判断根节点是否为空
self.root = AVLNode(val)
return
while True: # 判断左循环还是 又循环
if val < p.data: # 判断值的大小
if p.lchild: # 判断是否为空
p = p.lchild
else:
p.lchild = AVLNode(val)
p.lchild.parent = p
node=p.lchild
break
elif val > p.data:
if p.rchild:
p = p.rchild
else:
p.rchild = AVLNode(val)
p.rchild.parent = p
node=p.rchild
break
else:
return
#2.更新树的balance factor(bl)
while node.parent:
if node==node.parent.lchild: #如果node是插入到左孩子,即左边更沉了
#更新node.parent.bf-=1
g = node.parent.parent
x = node.parent
if node.parent.bf<0: #原来node.parent.bf=-1,插入后为-2
if node.bf>0:
n = self.rotate_left_right(node.parent, node)
else:
n = self.rotate_right(node.parent, node)
elif node.parent.bf>0: #原来node.parent.bf=1,插入后为0
node.parent.bf=0
break
else: #原来node.parent.bf=0,插入后为-1
node.parent.bf=-1
node=node.parent
continue
else:#如果node是插入到右孩子,即右边更沉了
#更新node.parent.bf+=1
g = node.parent.parent
x = node.parent
if node.parent.bf>0: #原来node.parent.bf=1,插入后为2
if node.bf<0:
n=self.rotate_right_left(node.parent,node)
else:
n=self.rotate_left(node.parent,node)
elif node.parent.bf<0: #原来node.parent.bf=-1,插入后为0
node.parent.bf=0
break
else: #原来node.parent.bf=0,插入后为1
node.parent.bf=1
node=node.parent
continue
n.parent = g
if g:
if x==g.lchild:
g.lchild = n
else:
g.rchild=n
break
else:
self.root = n
break
li=[i for i in range(100)]
import random
random.shuffle(li)
tree=AVLTree(li)
tree.pre_order(tree.root)
print('')
tree.in_order(tree.root)
node=AVLNode(3)