python实现AVL树

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)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值