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的右子树执行插入时的类似参数。
只需要在添加新节点时重置树的高度,但不需要旋转。