AVL树
AVL树是二元搜索树,遵循每个节点的平衡条件。
平衡条件约束每个节点的子树高度相差不超过1。
AVL trees are binary search trees that obey a balance condition at each node.
The balance condition constrains the height of the subtrees at each node to differ by no more than 1.
二叉树的高度
二叉树的高度是从根到叶的最长路径的长度。
具有一个节点的二叉树的高度为0。
按照惯例,空二进制树的高度为-1。
Height of Binary Trees
The height of a binary tree is the length of the longest path from the root to a leaf.
A binary tree with one node has height 0.
An empty binary tree is has height -1 by convention.
AVL树的例子(Examples of AVL Trees)
非AVL树(A non-AVL Tree)
Root 7: Height: 0
Root 20: Height: 2
建立AVL树(Building AVL Trees)
AVL树是通过从空的二叉树开始并一次添加一个元素来构建的。
对任何二叉搜索树进行添加,然后执行操作以恢复AVL平衡条件。
AVL trees are built by starting with an empty binary tree and adding elements one at time.
Additions are made as to any binary search tree, then an operation is executed to restore the AVL balance condition.
为了平衡自身,AVL树可以执行以下四种旋转
左旋转
右旋
左右旋转(双旋转)
左右旋转(双旋转)
To balance itself, an AVL tree may perform the following four kinds of rotations
Left rotation
Right rotation
Left-Right rotation (Double Rotation)
Right-Left rotation (Double Rotation)
LL不平衡
当N和N的左子节点K都是左重时,LL不平衡在节点N处发生。
LL imbalance
An LL imbalance occurs at a node N with a left child K when N and K are both left-heavy.
如果节点的左子树具有比其右子树更高的高度,则节点是左重的。
通过在具有不平衡的节点处执行单个右旋转来校正LL不平衡
A node is left-heavy if its left subtree has greater height then its right subtree.
An LL imbalance is corrected by executing a single right rotation at the node with the imbalance
纠正LL不平衡(Correcting LL Imbalances)
RR不平衡
•当N和M都是右重时,在具有右子M的节点N处发生RR不平衡。
•RR不平衡是LL不平衡的镜像。
RR Imbalance
• An RR imbalance occurs at a node N with a right child M when N and M are both right-heavy.
• An RR imbalance is the mirror image of an LL imbalance.
纠正RR不平衡
•通过在具有不平衡的节点处执行单个左旋转来校正RR不平衡。
Correcting RR Imbalances
• An RR imbalance is corrected by executing a single left rotation at the node with the imbalance.
LR不平衡
当N为左重且K为右重时,LR不平衡发生在具有左子K的节点N处。
LR imbalance
An LR imbalance occurs at a node N with a left child K when N is left-heavy and K is right- heavy.
纠正LR不平衡
通过在具有不平衡的节点处执行双LR旋转来校正LR不平衡。
Correcting An LR Imbalance
An LR imbalance is corrected by executing a double LR rotation at the node with the imbalance.
•通过在具有不平衡的节点处执行双LR旋转来校正LR不平衡。
• An LR imbalance is corrected by executing a double LR rotation at the node with the imbalance.
RL不平衡(RL imbalance)
•当N为右重且K为左重时,在具有右子K的节点N处发生RL不平衡。
• An RL imbalance occurs at a node N with a right child K when N is right-heavy and K is left- heavy.
纠正RL不平衡•左右旋转
Correcting RL imbalance • Right-Left Rotation