class Node(object):
def __init__(self, val):
self.val = val
self.lchild = None
self.rchild = None
class TreeNode():
def height(self, root):
if root == None:
return 0
else:
return root.height
def LL(self, root): # 右旋
node = root.lchild
root.lchild = node.rchild
node.rchild = root
root.height = max(self.height(root.lchild), self.height(root.rchild)) + 1
node.height = max(self.height(node.lchild), self.height(root.rchild)) + 1
return node
def RR(self, root): # 左旋
node = root.rchild
root.rchild = node.lchild
node.lchild = root
root.height = max(self.height(root.rchild), self.height(root.lchild)) + 1
node.height = max(self.height(node.lchild), self.height(root.rchild)) + 1
return node
def LR(self, root): # 先左旋再右旋
root.lchild = self.RR(root.lchild)
return self.LL(root)
def RL(self, root): # 先右旋再左旋
root.rchild = self.LL(root.rchild)
return self.RR(root)
# 插入数据
def insert(self, root, val):
if root == None:
root = Node(val)
else:
if val < root.val:
root.lchild = self.insert(root.lchild, val)
if abs(self.height(root.lchild) - self.height(root.rchild)) > 1:
if val < root.lchild.val:
root = self.LL(root)
else:
root = self.LR(root)
else:
root.rchild = self.insert(root.rchild, val)
if abs(self.height(root.lchild) - self.height(root.rchild)) > 1:
if val > root.rchild.val:
root = self.RR(root)
else:
root = self.RL(root)
root.height = max(self.height(root.lchild), self.height(root.rchild)) + 1
return root
# 查询
def find(self, root, val):
if root is None:
return False
else:
if root.val == val:
return True
else:
if val < root.val:
return self.find(root.lchild, val)
else:
return self.find(root.rchild, val)
def pre_order(self, root):
if root is None:
return
print(root.val, end=" ")
self.pre_order(root.lchild)
self.pre_order(root.rchild)
t = TreeNode()
root = None
for item in [4,3,2,1]:
root = t.insert(root, item)
print("二叉树的高度为%d"%(t.height(root)))
t.pre_order(root)
python实现AVL树
最新推荐文章于 2022-12-31 15:38:34 发布