AVL trees

AVL树是一种自平衡二叉查找树,其特点是在任何节点的左子树和右子树高度差不超过1。插入和删除操作可能导致不平衡,需要通过单旋或双旋来调整。在递归插入过程中,当子树高度差为2时执行旋转。平衡条件保证了搜索、插入和删除操作的时间复杂度为O(logn)。
摘要由CSDN通过智能技术生成

AVL trees(自平衡二叉查找树/高度平衡树)

平衡因子:左子树高减去右子树高
AVL的平衡因子绝对值不大于1
Recursive(递归) definition:
The sub-trees of every node differ in height by at most one.
Every sub-tree is an AVL tree.
Height of an empty tree is -1
Height of a single node is 0

若插入导致不平衡,则需要以插入路径上离节点最近的平衡因子绝对值大于1的节点为根的树进行调整

operation

Search, as for BSTs
Insert is the same as for BST but
May have to fix the tree after insertion to restore the balance condition
Can always do this via a modification known as a rotation
Single rotation or double rotation
Similarly for deletion
搜索,如BST
插入与BST相同,但插入后可能必须修复树才能恢复平衡状态
总是可以通过一种称为旋转的修改来实现这一点
单圈或双圈
删除时也是如此
Note that the balance condition ensures that search, insert and delete operations are all O(log n), where n is the number of nodes
请注意,平衡条件确保搜索、插入和删除操作都是O(logn),其中n是节点数
balancing is O(1)
在这里插入图片描述
在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

AVL tree insert

Let x be the deepest node where an imbalance occurs.
Four cases to consider.

The insertion is in the
left subtree of the left child of x.
right subtree of the left child of x.
left subtree of the right child of x.
right subtree of the right child of x.

Cases 1 & 4 are solved by a single rotation.
Cases 2 & 3 are solved by a double rotation.

设x是发生不平衡的最深节点。
需要考虑的四个案例。
插入在
x的左子的左子树。
x的左子的右子树。
x的右子的左子树。
x的右子的右子树。
情况1和4通过一次旋转即可解决。
情况2和3通过双重旋转解决。

When do I need to do a rotation?

During recursive implementation of insert for AVL tree (value e):

When insertion has been performed to a left subtree of node p:
if height of subtrees of p differ by 2, need rotation:
if the new root of left subtree < e need a single right rotation
else need a double left right rotation

Similar argument for when insertion has been performed to a right subtree of node p.

Only need to reset the heights of the tree when new node added, but no rotation required.
在递归实现插入AVL树(值e)期间:
当已经对节点p的左子树执行了插入时:
如果p的子树的高度相差2,则需要旋转:
如果左子树<e的新根需要一个右旋转
否则需要左右两次旋转
对节点p的右子树执行插入时的类似参数。
只需要在添加新节点时重置树的高度,但不需要旋转。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值