平衡二叉树(AVL)原理透析和编码解密

原文出自:http://dsqiu.iteye.com/blog/1705772

平衡二叉树(AVL)原理透析和编码解密

 

本文内容框架:

§1 AVL树定义

§2 AVL树平衡化旋转

  §3 AVL树插入删除

§4 AVL树高度分析

§5 小结

 

 

§1 AVL树定义

 

1 AVL树的定义(附件上有完整的AVL树实现)

高度平衡的二叉搜索树

一棵AVL树或者是空树,或者是具有下列性质的二叉搜索树:它的左子树和右子树都是AVL树,且左子树和右子树的高度之差的绝对值不超过1。

《平衡二叉树(AVL)原理透析和编码解密》

高度不平衡的二叉搜索树       高度平衡的二叉搜索树

结点的平衡因子balance (balance factor)

1、每个结点附加一个数字,给出该结点右子树的高度减去左子树的高度所得的高度差。这个数字即为结点的平衡因子balance 。

2、根据AVL树的定义,任一结点的平衡因子只能取 -1,0和 1。

3、如果一个结点的平衡因子的绝对值大于1,则这棵二叉搜索树就失去了平衡,不再是AVL树。

4、如果一棵二叉搜索树是高度平衡的,它就成为 AVL树。如果它有n个结点,其高度可保持在O(log2n),平均搜索长度也可保持在O(log2n)。

AVL树的结点定义

 

Cpp代码  

  1. #ifndef __BIN_TREE_NODE_H__  
  2. #define __BIN_TREE_NODE_H__  
  3.   
  4. #define LH 1                                // 左高  
  5. #define EH 0                                // 等高  
  6. #define RH -1                               // 右高  
  7.   
  8. // 二叉平衡树结点类  
  9. template <class ElemType>  
  10. struct BinAVLTreeNode  
  11. {  
  12. // 数据成员:  
  13.     ElemType data;                          // 数据域  
  14.     int bf;                                 // 结点的平衡因子  
  15.     BinAVLTreeNode<ElemType> *leftChild;  // 左孩子指针域  
  16.     BinAVLTreeNode<ElemType> *rightChild; // 右孩子指针域  
  17.   
  18. //  构造函数:  
  19.     BinAVLTreeNode();                       // 无参数的构造函数   
  20.     BinAVLTreeNode(const ElemType &val,     // 已知数据元素值,平衡因子和指向左右孩子的指针构造一个结点  
  21.         int bFactor = 0,  
  22.         BinAVLTreeNode<ElemType> *lChild = NULL,   
  23.         BinAVLTreeNode<ElemType> *rChild = NULL);  
  24. };  
  25.   
  26. // 二叉平衡树结点类的实现部分  
  27. template <class ElemType>  
  28. BinAVLTreeNode<ElemType>::BinAVLTreeNode()  
  29. // 操作结果:构造一个叶结点  
  30. {  
  31.     bf = 0;                         // 平衡因子  
  32.     leftChild = rightChild = NULL;  // 叶结点左右孩子为空  
  33. }  
  34.   
  35. template <class ElemType>  
  36. BinAVLTreeNode<ElemType>::BinAVLTreeNode(const ElemType &val, int bFactor,   
  37.                                    BinAVLTreeNode<ElemType> *lChild,   
  38.                                    BinAVLTreeNode<ElemType> *rChild)  
  39.   
  40. // 操作结果:构造一个数据域为val,平衡因子为bFactor,左孩子为lChild,右孩子为rChild的结点  
  41. {     
  42.     data = val;                     // 数据元素值  
  43.     bf = bFactor;                   // 平衡因子  
  44.     leftChild = lChild;             // 左孩子  
  45.     rightChild = rChild;            // 右孩子  
  46. }  
  47.   
  48. #endif  

 

AVL树的类定义

 

Cpp代码  

  1. #ifndef __BINNARY_TREE_H__  
  2. #define __BINNARY_TREE_H__  
  3.   
  4. #include “lk_queue.h”                   // 链队列  
  5. #include “lk_stack.h”                   // 链栈  
  6. #include “bin_avl_tree_node.h”          // 二叉平衡树结点类  
  7. enum StatusCode {SUCCESS, FAIL, UNDER_FLOW, OVER_FLOW,RANGE_ERROR, DUPLICATE_ERROR,  
  8.     NOT_PRESENT, ENTRY_INSERTED, ENTRY_FOUND, VISITED, UNVISITED};  
  9. // 二叉平衡树类  
  10. template <class ElemType, class KeyType>  
  11. class BinaryAVLTree  
  12. {  
  13. protected:  
  14. //  二叉平衡树的数据成员:  
  15.     BinAVLTreeNode<ElemType> *root;  
  16.   
  17. //  辅助函数:  
  18.     BinAVLTreeNode<ElemType> *CopyTreeHelp(BinAVLTreeNode<ElemType> *copy); // 复制二叉平衡树  
  19.     void DestroyHelp(BinAVLTreeNode<ElemType> * &r);                      // 销毁以r为根二叉平衡树  
  20.     void PreOrderHelp(BinAVLTreeNode<ElemType> *r, void (*Visit)(const ElemType &)) const;    // 先序遍历  
  21.     void InOrderHelp(BinAVLTreeNode<ElemType> *r, void (*Visit)(const ElemType &)) const// 中序遍历  
  22.     void PostOrderHelp(BinAVLTreeNode<ElemType> *r, void (*Visit)(const ElemType &)) const;   // 后序遍历  
  23.     int HeightHelp(const BinAVLTreeNode<ElemType> *r) const;  // 返回二叉平衡树的高  
  24.     int NodeCountHelp(const BinAVLTreeNode<ElemType> *r) const;// 返回二叉平衡树的结点个数  
  25.     BinAVLTreeNode<ElemType> *ParentHelp(BinAVLTreeNode<ElemType> *r,   
  26.         const BinAVLTreeNode<ElemType> *cur) const;           // 返回cur的双亲  
  27.     BinAVLTreeNode<ElemType> *SearchHelp(const KeyType &key, BinAVLTreeNode<ElemType> *&f) const;     
  28.         // 查找关键字为key的数据元素  
  29.   
  30.     BinAVLTreeNode<ElemType> *SearchHelp(const KeyType &key, BinAVLTreeNode<ElemType> *&f,  
  31.         LinkStack<BinAVLTreeNode<ElemType> *> &s); // 返回指向关键字为key的元素的指针,用f返回其双亲  
  32.     void LeftRotate(BinAVLTreeNode<ElemType> *&subRoot);  
  33.         // 对以subRoot为根的二叉树作左旋处理,处理之后subRoot指向新的树根结点,也就是旋转处理前的右子  
  34.         // 树的根结点  
  35.     void RightRotate(BinAVLTreeNode<ElemType> *&subRoot);  
  36.         // 对以subRoot为根的二叉树作右旋处理,处理之后subRoot指向新的树根结点,也就是旋转处理前的左子  
  37.         // 树的根结点  
  38.     void InsertLeftBalance(BinAVLTreeNode<ElemType> *&subRoot);  
  39.         // 对以subRoot为根的二叉树插入时作左平衡处理,处理后subRoot指向新的树根结点  
  40.     void InsertRightBalance(BinAVLTreeNode<ElemType> *&subRoot);  
  41.         // 对以subRoot为根的二叉树插入时作右平衡处理,处理后subRoot指向新的树根结点  
  42.     void InsertBalance(const ElemType &elem, LinkStack< BinAVLTreeNode<ElemType> *> &s);  
  43.         // 从插入结点elem根据查找路径进行回溯,并作平衡处理  
  44.     void DeleteLeftBalance(BinAVLTreeNode<ElemType> *&subRoot, bool &isShorter);  
  45.         // 对以subRoot为根的二叉树删除时作左平衡处理,处理后subRoot指向新的树根结点  
  46.     void DeleteRightBalance(BinAVLTreeNode<ElemType> *&subRoot, bool &isShorter);  
  47.         // 对以subRoot为根的二叉树删除时作右平衡处理,处理后subRoot指向新的树根结点  
  48.     void DeleteBalance(const KeyType &key, LinkStack<BinAVLTreeNode<ElemType> *> &s);  
  49.         // 从删除结点根据查找路径进行回溯,并作平衡处理  
  50.     void DeleteHelp(const KeyType &key, BinAVLTreeNode<ElemType> *&p,  
  51.         LinkStack< BinAVLTreeNode<ElemType> *> &s);     // 删除p指向的结点  
  52.   
  53. public:  
  54. //  二叉平衡树方法声明及重载编译系统默认方法声明:  
  55.     BinaryAVLTree();                                        // 无参数的构造函数  
  56.     virtual ~BinaryAVLTree();                               // 析构函数  
  57.     BinAVLTreeNode<ElemType> *GetRoot() const;                // 返回二叉平衡树的根  
  58.     bool Empty() const;                                     // 判断二叉平衡树是否为空  
  59.     StatusCode GetElem(BinAVLTreeNode<ElemType> *cur, ElemType &e) const;  
  60.         // 用e返回结点数据元素值  
  61.     StatusCode SetElem(BinAVLTreeNode<ElemType> *cur, const ElemType &e);  
  62.         // 将结cur的值置为e  
  63.     void InOrder(void (*Visit)(const ElemType &)) const;    // 二叉平衡树的中序遍历     
  64.     void PreOrder(void (*Visit)(const ElemType &)) const;   // 二叉平衡树的先序遍历  
  65.     void PostOrder(void (*Visit)(const ElemType &)) const;  // 二叉平衡树的后序遍历  
  66.     void LevelOrder(void (*Visit)(const ElemType &)) const// 二叉平衡树的层次遍历  
  67.     int NodeCount() const;                                  // 求二叉平衡树的结点个数  
  68.     BinAVLTreeNode<ElemType> *Search(const KeyType &key) const;// 查找关键字为key的数据元素  
  69.     bool Insert(const ElemType &e);                         // 插入数据元素e  
  70.     bool Delete(const KeyType &key);                        // 删除关键字为key的数据元素  
  71.     BinAVLTreeNode<ElemType> *LeftChild(const BinAVLTreeNode<ElemType> *cur) const;  
  72.         // 返回二叉平衡树结点cur的左孩子  
  73.     BinAVLTreeNode<ElemType> *RightChild(const BinAVLTreeNode<ElemType> *cur) const;  
  74.         // 返回二叉平衡树结点cur的右孩子  
  75.     BinAVLTreeNode<ElemType> *Parent(const BinAVLTreeNode<ElemType> *cur) const;  
  76.         // 返回二叉平衡树结点cur的双亲  
  77.     int Height() const;                                     // 求二叉平衡树的高  
  78.     BinaryAVLTree(const ElemType &e);                       // 建立以e为根的二叉平衡树  
  79.     BinaryAVLTree(const BinaryAVLTree<ElemType, KeyType> &copy);  // 复制构造函数  
  80.     BinaryAVLTree(BinAVLTreeNode<ElemType> *r);               // 建立以r为根的二叉平衡树  
  81.     BinaryAVLTree<ElemType, KeyType> &operator=(const BinaryAVLTree<ElemType, KeyType>& copy);  // 赋值语句重载  
  82. };  

 

 

 

§2 AVL树平衡化旋转

 

 

2 平衡化旋转

1、如果在一棵平衡的二叉搜索树中插入一个新结点,造成了不平衡。
此时必须调整树的结构,使之平衡化。

2、平衡化旋转有两类:

单旋转 (左旋和右旋)  双旋转 (左平衡和右平衡)

3、每插入一个新结点时,AVL树中相关结点的平衡状态会发生改变。因此,在插入一个新结点后,需要从插入位置沿通向根的路径回溯,检查各结点的平衡因子(左、右子树的高度差)。

4、如果在某一结点发现高度不平衡,停止回溯。

5、从发生不平衡的结点起,沿刚才回溯的路径取直接下两层的结点。

6、 如果这三个结点处于一条直线上,则采用单旋转进行平衡化。单旋转可按其方向分为左单旋转和右单旋转,其中一个是另一个的镜像,其方向与不平衡的形状相关。

7、如果这三个结点处于一条折线上,则采用双旋转进行平衡化。双旋转分为先左后右和先右后左两类。

《平衡二叉树(AVL)原理透析和编码解密》《平衡二叉树(AVL)原理透析和编码解密》《平衡二叉树(AVL)原理透析和编码解密》《平衡二叉树(AVL)原理透析和编码解密》
右单旋转左单旋转左右双旋转右左双旋转

1、左单旋转 (RotateLeft )

《平衡二叉树(AVL)原理透析和编码解密》

(1)如果在子树E中插入一个新结点,该子树高度增1导致结点A的平衡因子变成+2,出现不平衡。

(2)沿插入路径检查三个结点A、C和E。它们处于一条方向为“\”的直线上,需要做左单旋转。

(3)以结点C为旋转轴,让结点A反时针旋转。

左单旋转的算法

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::LeftRotate(BinAVLTreeNode<ElemType> *&subRoot)  
  3. // 操作结果: 对以subRoot为根的二叉树作左旋处理,处理之后subRoot指向新的树根结点,  
  4. //  也就是旋转处理前的右子树的根结点  
  5. {  
  6.     BinAVLTreeNode<ElemType> *ptrRChild;  
  7.     ptrRChild = subRoot->rightChild;         // ptrRChild指向subRoot右孩子  
  8.     subRoot->rightChild = ptrRChild->leftChild;   // ptrRChild的左子树链接为subRoot的右子树  
  9.     ptrRChild->leftChild = subRoot;              // subRoot链接为ptrRChild的左孩子  
  10.     subRoot = ptrRChild;                        // subRoot指向新的根结点  
  11. }  

 

 

2、右单旋转 (RotateRight )

《平衡二叉树(AVL)原理透析和编码解密》

(1)在左子树D上插入新结点使其高度增1,导致结点A的平衡因子增到 -2,造成了不平衡。

(2) 为使树恢复平衡,从A沿插入路径连续取3个结点A、B和D,它们处于一条方向为“/”的直线上,需要做右单旋转。

(3) 以结点B为旋转轴,将结点A顺时针旋转。

右单旋转的算法

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::RightRotate(BinAVLTreeNode<ElemType> *&subRoot)  
  3. // 操作结果: 对以subRoot为根的二叉树作右旋处理,处理之后subRoot指向新的树根结点,  
  4. //  也就是旋转处理前的左子树的根结点  
  5. {  
  6.     BinAVLTreeNode<ElemType> *pLChild;  
  7.     pLChild = subRoot->leftChild;                // pLChild指向subRoot左孩子  
  8.     subRoot->leftChild = pLChild->rightChild; // pLChild的右子树链接为subRoot的左子树  
  9.     pLChild->rightChild = subRoot;               // subRoot链接为pLChild的右孩子  
  10.     subRoot = pLChild;                          // subRoot指向新的根结点  
  11. }  

 

 

3、先左后右双旋转 (RotationLeftRight)

《平衡二叉树(AVL)原理透析和编码解密》

(1)在子树F或G中插入新结点,该子树的高度增1。结点A的平衡因子变为 -2,发生了不平衡。

(2) 从结点A起沿插入路径选取3个结点A、B和E,它们位于一条形如“?”的折线上,因此需要进行先左后右的双旋转。

(3)首先以结点E为旋转轴,将结点B反时针旋转,以E代替原来B的位置,做左单旋转。

(4) 再以结点E为旋转轴,将结点A顺时针旋转,做右单旋转。使之平衡化。

左平衡化的算法

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::InsertLeftBalance(BinAVLTreeNode<ElemType> *&subRoot)  
  3. // 操作结果: 对以subRoot为根的二叉树插入时作左平衡处理,插入结点在subRoot左子树上,处理后  
  4. //  subRoot指向新的树根结点  
  5. {  
  6.     BinAVLTreeNode<ElemType> *ptrLChild, *ptrLRChild;   
  7.     ptrLChild  = subRoot->leftChild; // ptrLChild指向subRoot左孩子  
  8.     switch (ptrLChild->bf)  
  9.     {   // 根据subRoot的左子树的平衡因子作相应的平衡处理  
  10.     case LH:                            // 插入结点在subRoot的左孩子的左子树上,作单右旋处理  
  11.         subRoot->bf = ptrLChild->bf = EH;// 平衡因子都为0  
  12.         RightRotate(subRoot);           // 右旋  
  13.         break;  
  14.     case RH:                            // 插入结点在subRoot的左孩子的右子树上,作先左旋后右旋处理  
  15.         ptrLRChild = ptrLChild->rightChild;// ptrLRChild指向subRoot的左孩子的右子树的根  
  16.         switch (ptrLRChild->bf)  
  17.         {   // 修改subRoot及左孩子的平衡因子  
  18.         case LH:                        // 插入结点在ptrLRChild的左子树上  
  19.             subRoot->bf = RH;  
  20.             ptrLChild->bf = EH;  
  21.             break;  
  22.         case EH:                        // 插入前ptrLRChild为空,ptrLRChild指向插入结点  
  23.             subRoot->bf = ptrLChild->bf = EH;  
  24.             break;  
  25.         case RH:                        // 插入结点在ptrLRChild的左子树上  
  26.             subRoot->bf = EH;  
  27.             ptrLChild->bf = LH;  
  28.             break;  
  29.         }  
  30.         ptrLRChild->bf = 0;  
  31.         LeftRotate(subRoot->leftChild);  // 对subRoot左子树作左旋处理  
  32.         RightRotate(subRoot);           // 对subRoot作右旋处理  
  33.     }  
  34. }  

 

 

4、先右后左双旋转 (RotationRightLeft)

《平衡二叉树(AVL)原理透析和编码解密》

(1)右左双旋转是左右双旋转的镜像。

(2) 在子树F或G中插入新结点,该子树高度增1。结点A的平衡因子变为2,发生了不平衡。

(3) 从结点A起沿插入路径选取3个结点A、C和D,它们位于一条形如“?”的折线上,需要进行先右后左的双旋转。

(4)首先做右单旋转:以结点D为旋转轴,将结点C顺时针旋转,以D代替原来C的位置。

(5) 再做左单旋转:以结点D为旋转轴,将结点A反时针旋转,恢复树的平衡。

右平衡化的算法

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::InsertRightBalance(BinAVLTreeNode<ElemType> *&subRoot)  
  3. // 操作结果: 对以subRoot为根的二叉树插入时作右平衡处理,插入结点在subRoot左子树上,处理后  
  4. //  subRoot指向新的树根结点  
  5. {  
  6.     BinAVLTreeNode<ElemType> *ptrRChild, *ptrRLChild;   
  7.     ptrRChild  = subRoot->rightChild;    // ptrRChild指向subRoot右孩子  
  8.     switch (ptrRChild->bf)  
  9.     {   // 根据subRoot的右子树的平衡因子作相应的平衡处理  
  10.     case RH:                            // 插入结点在subRoot的右孩子的右子树上,作单左旋处理  
  11.         subRoot->bf = ptrRChild->bf = EH;// 平衡因子都为0  
  12.         LeftRotate(subRoot);            // 左旋  
  13.         break;  
  14.     case LH:                            // 插入结点在subRoot的右孩子的左子树上,作先右旋后左旋处理  
  15.         ptrRLChild = ptrRChild->leftChild;// ptrRLChild指向subRoot的右孩子的左子树的根  
  16.         switch (ptrRLChild->bf)  
  17.         {   // 修改subRoot及右孩子的平衡因子  
  18.         case RH:                        // 插入结点在ptrRLChild的右子树上  
  19.             subRoot->bf = LH;  
  20.             ptrRChild->bf = EH;  
  21.             break;  
  22.         case EH:                        // 插入前ptrRLChild为空,ptrRLChild指向插入结点  
  23.             subRoot->bf = ptrRChild->bf = EH;  
  24.             break;  
  25.         case LH:                        // 插入结点在ptrRLChild的左子树上  
  26.             subRoot->bf = EH;  
  27.             ptrRChild->bf = RH;  
  28.             break;  
  29.         }  
  30.         ptrRLChild->bf = 0;  
  31.         RightRotate(subRoot->rightChild);// 对subRoot右子树作右旋处理  
  32.         LeftRotate(subRoot);            // 对subRoot作左旋处理  
  33.     }  
  34. }  

 

 

 

§3 AVL树插入删除

 

3 AVL树的插入和删除

AVL树的插入:

1、在向一棵本来是高度平衡的AVL树中插入一个新结点时,如果树中某个结点的平衡因子的绝对值 |balance| > 1,则出现了不平衡,需要做平衡化处理。

2、在AVL树上定义了重载操作“>>”和“<<”,以及中序遍历的算法。利用这些操作可以执行AVL树的建立和结点数据的输出。

3、 算法从一棵空树开始,通过输入一系列对象的关键码,逐步建立AVL树。在插入新结点时使用了前面所给的算法进行平衡旋转。

例,输入关键码序列为 { 16, 3, 7, 11, 9, 26, 18, 14, 15 },插入和调整过程如下。

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

从空树开始的建树过程

1、下面的算法将通过递归方式将新结点作为叶结点插入并逐层修改各结点的平衡因子。

2、 在发现不平衡时立即执行相应的平衡化旋转操作,使得树中各结点重新平衡化。

3、 在程序中,用变量success记载新结点是否存储分配成功,并用它作为函数的返回值。

4、算法从树的根结点开始,递归向下找插入位置。在找到插入位置(空指针)后,为新结点动态分配存储空间,将它作为叶结点插入,并置success为1,再将taller置为1,以表明插入成功。在退出递归沿插入路径向上返回时做必要的调整。

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::InsertBalance(const ElemType &e,  
  3.     LinkStack<BinAVLTreeNode<ElemType> *> &s)  
  4. // 操作结果: 从插入元素e根据查找路径进行回溯,并作平衡处理  
  5. {  
  6.     bool isTaller = true;  
  7.     while (!s.Empty() && isTaller)  
  8.     {  
  9.         BinAVLTreeNode<ElemType> *ptrCurNode, *ptrParent;  
  10.         s.Pop(ptrCurNode);          // 取出待平衡的结点  
  11.         if (s.Empty())  
  12.         {   // ptrCurNode已为根结点,ptrParent为空  
  13.             ptrParent = NULL;  
  14.         }  
  15.         else  
  16.         {   // ptrCurNode不为根结点,取出双亲ptrParent  
  17.             s.Top(ptrParent);  
  18.         }  
  19.   
  20.         if (e < ptrCurNode->data)  
  21.         {   // e插入在ptrCurNode的左子树上  
  22.             switch (ptrCurNode->bf)  
  23.             {   // 检查ptrCurNode的平衡度  
  24.             case LH:                        // 插入后ptrCurNode->bf=2, 作左平衡处理  
  25.                 if (ptrParent == NULL)  
  26.                 {   // 已回溯到根结点  
  27.                     InsertLeftBalance(ptrCurNode);    
  28.                     root = ptrCurNode;      // 转换后ptrCurNode为新根  
  29.                 }  
  30.                 else if (ptrParent->leftChild == ptrCurNode)  
  31.                 {   // ptrParent左子树作平衡处理  
  32.                     InsertLeftBalance(ptrParent->leftChild);  
  33.                 }  
  34.                 else  
  35.                 {   // ptrParent右子树作平衡处理  
  36.                     InsertLeftBalance(ptrParent->rightChild);  
  37.                 }  
  38.                 isTaller = false;  
  39.                 break;  
  40.             case EH:                    // 插入后ptrCurNode->bf=LH  
  41.                 ptrCurNode->bf = LH;  
  42.                 break;    
  43.             case RH:                    // 插入后ptrCurNode->bf=EH  
  44.                 ptrCurNode->bf = EH;  
  45.                 isTaller = false;  
  46.                 break;  
  47.             }  
  48.         }  
  49.         else  
  50.         {   // e插入在ptrCurNode的右子树上  
  51.             switch (ptrCurNode->bf)  
  52.             {   // 检查ptrCurNode的平衡度  
  53.             case RH:                        // 插入后ptrCurNode->bf=-2, 作右平衡处理  
  54.                 if (ptrParent == NULL)  
  55.                 {   // 已回溯到根结点  
  56.                     InsertRightBalance(ptrCurNode);  
  57.                     root = ptrCurNode;      // 转换后ptrCurNode为新根  
  58.                 }  
  59.                 else if (ptrParent->leftChild == ptrCurNode)  
  60.                 {   // ptrParent左子树作平衡处理  
  61.                     InsertRightBalance(ptrParent->leftChild);  
  62.                 }  
  63.                 else  
  64.                 {   // ptrParent右子树作平衡处理  
  65.                     InsertRightBalance(ptrParent->rightChild);  
  66.                 }  
  67.                 isTaller = false;  
  68.                 break;  
  69.             case EH:                        // 插入后ptrCurNode->bf=RH  
  70.                 ptrCurNode->bf = RH;  
  71.                 break;  
  72.             case LH:                        // 插入后ptrCurNode->bf=EH  
  73.                 ptrCurNode->bf = EH;  
  74.                 isTaller = false;  
  75.                 break;  
  76.             }  
  77.         }  
  78.     }  
  79. }  
  80.   
  81. template <class ElemType, class KeyType>  
  82. bool BinaryAVLTree<ElemType, KeyType>::Insert(const ElemType &e)  
  83. // 操作结果: 插入数据元素e  
  84. {  
  85.     BinAVLTreeNode<ElemType> *f;  
  86.     LinkStack< BinAVLTreeNode<ElemType> *> s;  
  87.     if (SearchHelp(e, f, s) == NULL)  
  88.     {   // 查找失败, 插入成功  
  89.         BinAVLTreeNode<ElemType> *p;      // 插入的新结点  
  90.         p = new BinAVLTreeNode<ElemType>(e);// 生成插入结点  
  91.         p->bf = 0;  
  92.         if (Empty())  
  93.         {   // 空二叉树,新结点为根结点  
  94.             root = p;  
  95.         }  
  96.         else if (e < f->data)  
  97.         {   // e更小,插入结点为f的左孩子  
  98.             f->leftChild = p;  
  99.         }  
  100.         else  
  101.         {   // e更大,插入结点为f的右孩子  
  102.             f->rightChild = p;  
  103.         }  
  104.   
  105.         InsertBalance(e, s);// 插入结点后作平衡处理  
  106.         return true;          
  107.     }  
  108.     else  
  109.     {   // 查找成功, 插入失败  
  110.         return false;  
  111.     }  
  112. }  

 

 

 

AVL树的删除

1、如果被删结点x最多只有一个子女,那么问题比较简单。如果被删结点x有两个子女,首先搜索 x 在中序次序下的直接前驱 y (同样可以找直接后继)。再把 结点y 的内容传送给结点x,现在问题转移到删除结点 y。 把结点y当作被删结点x。

2、 将结点x从树中删去。因为结点x最多有一个子女,我们可以简单地把x的双亲结点中原来指向x的指针改指到这个子女结点;如果结点x没有子女,x双亲结点的相应指针置为NULL。然后将原来以结点x为根的子树的高度减1,

3、必须沿x通向根的路径反向追踪高度的变化对路径上各个结点的影响。

4、 用一个布尔变量 shorter 来指明子树的高度是否被缩短。在每个结点上要做的操作取决于 shorter 的值和结点的 balance,有时还要依赖子女的 balance 。

5、 布尔变量 shorter 的值初始化为True。然后对于从 x 的双亲到根的路径上的各个结点 p,在 shorter 保持为 True 时执行下面的操作。如果 shorter 变成False,算法终止。

6、case 1 : 当前结点p的balance为0。如果它的左子树或右子树被缩短,则它的 balance改为1或-1,同时 shorter 置为False。

7、case 2 : 结点p的balance不为0,且较高的子树被缩短,则p的balance改为0,同时 shorter 置为True。

《平衡二叉树(AVL)原理透析和编码解密》

8、case 3 : 结点p的balance不为0,且较矮的子树又被缩短,则在结点p发生不平衡。需要进行平衡化旋转来恢复平衡。令p的较高的子树的根为 q (该子树未被缩短),根据q的balance ,有如下3种平衡化操作。

9、case 3a : 如果q的balance为0,执行一个单旋转来恢复结点p的平衡,置shorter为False。

 

10、 case 3b : 如果q的balance与p的balance相同,则执行一个单旋转来恢复平衡,结点p和q的balance均改为0,同时置shorter为True。

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

11、case 3c : 如果p与q的balance相反,则执行一个双旋转来恢复平衡,先围绕 q 转再围绕 p 转。新的根结点的balance置为0,其它结点的balance相应处理,同时置shorter为True。

12、 在case 3a, 3b和3c的情形中,旋转的方向取决于是结点p的哪一棵子树被缩短。

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

 

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::DeleteLeftBalance(BinAVLTreeNode<ElemType> *&  
  3. subRoot, bool &isShorter)  
  4. // 操作结果: 对以subRoot为根的二叉树删除时作左平衡处理, 删除subRoot的左子树上的结点,处  
  5. //  理后subRoot指向新的树根结点  
  6. {  
  7.     BinAVLTreeNode<ElemType> *ptrRChild, *ptrRLChild;   
  8.     ptrRChild  = subRoot->rightChild;        // ptrRChild指向subRoot右孩子  
  9.     switch (ptrRChild->bf)  
  10.     {   // 根据subRoot的右子树的平衡因子作相应的平衡处理  
  11.     case RH:                                // 右高,作单左旋转  
  12.         subRoot->bf = ptrRChild->bf = EH; // 平衡因子都为0  
  13.         LeftRotate(subRoot);                // 左旋  
  14.         isShorter = true;  
  15.         break;  
  16.     case EH:                                // 等高,作单左旋转  
  17.         subRoot->bf = RH;  
  18.         ptrRChild->bf = LH;        
  19.         LeftRotate(subRoot);                // 左旋  
  20.         isShorter = false;  
  21.         break;  
  22.     case LH:                                // 左高,先右旋后左旋  
  23.         ptrRLChild = ptrRChild->leftChild;   // ptrRLChild指向subRoot的右孩子的左子树的根  
  24.         switch (ptrRLChild->bf)  
  25.         {   // 修改subRoot及右孩子的平衡因子  
  26.         case LH:  
  27.             subRoot->bf = EH;  
  28.             ptrRChild->bf = RH;  
  29.             isShorter = true;  
  30.             break;  
  31.         case EH:  
  32.             subRoot->bf = ptrRChild->bf = EH;  
  33.             isShorter = false;  
  34.             break;  
  35.         case RH:  
  36.             subRoot->bf = LH;  
  37.             ptrRChild->bf = EH;  
  38.             isShorter = true;  
  39.             break;  
  40.         }  
  41.         ptrRLChild->bf = 0;  
  42.         RightRotate(subRoot->rightChild);    // 对subRoot右子树作右旋处理  
  43.         LeftRotate(subRoot);                // 对subRoot作左旋处理  
  44.     }  
  45. }  
  46.   
  47. template <class ElemType, class KeyType>  
  48. void BinaryAVLTree<ElemType, KeyType>::DeleteRightBalance(BinAVLTreeNode<ElemType> *  
  49. &subRoot, bool &isShorter)  
  50. // 操作结果: 对以subRoot为根的二叉树删除时作右平衡处理, 删除subRoot的右子树上的结点,处  
  51. //  理后subRoot指向新的树根结点  
  52. {  
  53.     BinAVLTreeNode<ElemType> *ptrLChild, *ptrLRChild;   
  54.     ptrLChild  = subRoot->leftChild; // ptrLChild指向subRoot左孩子  
  55.     switch (ptrLChild->bf)  
  56.     {   // 根据subRoot的左子树的平衡因子作相应的平衡处理  
  57.     case LH:                        // 右高,作单右旋转  
  58.         subRoot->bf = ptrLChild->bf = EH;// 平衡因子都为0  
  59.         RightRotate(subRoot);           // 右旋  
  60.         isShorter = true;  
  61.         break;  
  62.     case EH:                        // 等高,作单右旋转  
  63.         subRoot->bf = LH;  
  64.         ptrLChild->bf = RH;          // 平衡因子都为0  
  65.         RightRotate(subRoot);           // 右旋  
  66.         isShorter = false;  
  67.         break;  
  68.     case RH:                        // 左高,先左旋后右旋  
  69.         ptrLRChild = ptrLChild->rightChild;// ptrLRChild指向subRoot的左孩子的右子树的根  
  70.         switch (ptrLRChild->bf)  
  71.         {   // 修改subRoot及左孩子的平衡因子  
  72.         case LH:  
  73.             subRoot->bf = RH;  
  74.             ptrLChild->bf = EH;  
  75.             isShorter = true;  
  76.             break;  
  77.         case EH:  
  78.             subRoot->bf = ptrLChild->bf = EH;  
  79.             isShorter = false;  
  80.             break;  
  81.         case RH:  
  82.             subRoot->bf = EH;  
  83.             ptrLChild->bf = LH;  
  84.             isShorter = true;  
  85.             break;  
  86.         }  
  87.         ptrLRChild->bf = 0;  
  88.         LeftRotate(subRoot->leftChild);  // 对subRoot左子树作左旋处理  
  89.         RightRotate(subRoot);           // 对subRoot作右旋处理  
  90.     }  
  91. }  
  92.   
  93. template <class ElemType, class KeyType>  
  94. void BinaryAVLTree<ElemType, KeyType>::DeleteBalance(const KeyType &key,   
  95. LinkStack<BinAVLTreeNode<ElemType> *> &s)  
  96. // 操作结果: 从删除结点根据查找路径进行回溯,并作平衡处理  
  97. {  
  98.     bool isShorter = true;  
  99.     while (!s.Empty() && isShorter)  
  100.     {  
  101.         BinAVLTreeNode<ElemType> *ptrCurNode, *ptrParent;  
  102.         s.Pop(ptrCurNode);                  // 取出待平衡的结点  
  103.         if (s.Empty())  
  104.         {   // ptrCurNode已为根结点,ptrParent为空  
  105.             ptrParent = NULL;  
  106.         }  
  107.         else  
  108.         {   // ptrCurNode不为根结点,取出双亲ptrParent  
  109.             s.Top(ptrParent);  
  110.         }  
  111.   
  112.         if (key < ptrCurNode->data)  
  113.         {   // 删除ptrCurNode的左子树上的结点  
  114.             switch (ptrCurNode->bf)  
  115.             {   // 检查ptrCurNode的平衡度  
  116.             case LH:                        // 左高  
  117.                 ptrCurNode->bf = EH;  
  118.                 break;  
  119.             case EH:                        // 等高  
  120.                 ptrCurNode->bf = RH;  
  121.                 isShorter = false;  
  122.                 break;  
  123.             case RH:                        // 右高  
  124.                 if (ptrParent == NULL)  
  125.                 {   // 已回溯到根结点  
  126.                     DeleteLeftBalance(ptrCurNode, isShorter);  
  127.                     root = ptrCurNode;      // 转换后ptrCurNode为新根  
  128.                 }  
  129.                 else if (ptrParent->leftChild == ptrCurNode)  
  130.                 {   // ptrParent左子树作平衡处理  
  131.                     DeleteLeftBalance(ptrParent->leftChild, isShorter);  
  132.                 }  
  133.                 else  
  134.                 {   // ptrParent右子树作平衡处理  
  135.                     DeleteLeftBalance(ptrParent->rightChild, isShorter);  
  136.                 }  
  137.                 break;  
  138.             }  
  139.         }  
  140.         else  
  141.         {   // 删除ptrCurNode的右子树上的结点  
  142.             switch (ptrCurNode->bf)  
  143.             {   // 检查ptrCurNode的平衡度  
  144.             case RH:                        // 右高  
  145.                 ptrCurNode->bf = EH;  
  146.                 break;  
  147.             case EH:                        // 等高  
  148.                 ptrCurNode->bf = LH;  
  149.                 isShorter = false;  
  150.                 break;  
  151.             case LH:                        // 左高  
  152.                 if (ptrParent == NULL)  
  153.                 {   // 已回溯到根结点  
  154.                     DeleteLeftBalance(ptrCurNode, isShorter);  
  155.                     root = ptrCurNode;      // 转换后ptrCurNode为新根  
  156.                 }  
  157.                 else if (ptrParent->leftChild == ptrCurNode)  
  158.                 {   // ptrParent左子树作平衡处理  
  159.                     DeleteLeftBalance(ptrParent->leftChild, isShorter);  
  160.                 }  
  161.                 else  
  162.                 {   // ptrParent右子树作平衡处理  
  163.                     DeleteLeftBalance(ptrParent->rightChild, isShorter);  
  164.                 }  
  165.                 break;  
  166.             }  
  167.         }  
  168.     }  
  169. }  
  170.   
  171. template <class ElemType, class KeyType>  
  172. void BinaryAVLTree<ElemType, KeyType>::DeleteHelp(const KeyType &key,   
  173. BinAVLTreeNode<ElemType> *&p, LinkStack< BinAVLTreeNode<ElemType> *> &s)  
  174. // 操作结果: 删除p指向的结点  
  175. {  
  176.     BinAVLTreeNode<ElemType> *tmpPtr, *tmpF;    
  177.     if (p->leftChild == NULL && p->rightChild == NULL)  
  178.     {   // p为叶结点  
  179.         delete p;  
  180.         p = NULL;  
  181.         DeleteBalance(key, s);  
  182.     }  
  183.     else if (p->leftChild == NULL)  
  184.     {   // p只有左子树为空  
  185.         tmpPtr = p;  
  186.         p = p->rightChild;  
  187.         delete tmpPtr;  
  188.         DeleteBalance(key, s);  
  189.     }  
  190.     else if (p->rightChild == NULL)  
  191.     {   // p只有右子树非空  
  192.         tmpPtr = p;  
  193.         p = p->leftChild;  
  194.         delete tmpPtr;  
  195.         DeleteBalance(key, s);  
  196.     }  
  197.     else  
  198.     {   // p左右子非空  
  199.         tmpF = p;  
  200.         s.Push(tmpF);  
  201.         tmpPtr = p->leftChild;  
  202.         while (tmpPtr->rightChild != NULL)  
  203.         {   // 查找p在中序序列中直接前驱tmpPtr及其双亲tmpF,tmpPtr无右子树为空  
  204.             tmpF = tmpPtr;  
  205.             s.Push(tmpF);  
  206.             tmpPtr = tmpPtr->rightChild;  
  207.         }  
  208.         p->data = tmpPtr->data;// 将tmpPtr指向结点的元素值赋值给tmpF指向结点的元素值  
  209.   
  210.         // 删除tmpPtr指向的结点  
  211.         if (tmpF->rightChild == tmpPtr)  
  212.         {   // 删除tmpF的右孩子  
  213.             DeleteHelp(key, tmpF->rightChild, s);  
  214.         }  
  215.         else  
  216.         {   // 删除tmpF的左孩子  
  217.             DeleteHelp(key, tmpF->leftChild, s);  
  218.         }  
  219.     }  
  220. }  
  221.   
  222. template <class ElemType, class KeyType>  
  223. bool BinaryAVLTree<ElemType, KeyType>::Delete(const KeyType &key)  
  224. // 操作结果: 删除关键字为key的结点  
  225. {  
  226.     BinAVLTreeNode<ElemType> *p, *f;  
  227.     LinkStack< BinAVLTreeNode<ElemType> *> s;  
  228.     p = SearchHelp(key, f, s);  
  229.     if ( p == NULL)  
  230.     {   // 查找失败, 删除失败  
  231.         return false;  
  232.     }  
  233.     else  
  234.     {   // 查找成功, 插入失败  
  235.         if (f == NULL)  
  236.         {   // 被删除结点为根结点  
  237.             DeleteHelp(key, root, s);  
  238.         }  
  239.         else if (key < f->data)  
  240.         {   // key更小,删除f的左孩子  
  241.             DeleteHelp(key, f->leftChild, s);  
  242.         }  
  243.         else  
  244.         {   // key更大,插入f的右孩子  
  245.             DeleteHelp(key, f->rightChild, s);  
  246.         }  
  247.         return true;          
  248.     }  
  249. }  

 

 

§4 AVL树高度分析

 

4 AVL树的高度分析

1、设在新结点插入前AVL树的高度为h,结点个数为n,则插入一个新结点的时间是O(h)。对于AVL树来说,h多大?

2、设 Nh 是高度为 h 的AVL树的最小结点数。根的一棵子树的高度为 h-1,另一棵子树的高度为 h-2,这两棵子树也是高度平衡的。因此有 N-1 = 0 (空树) N0 = 1 (仅有根结点) Nh = Nh-1 + Nh-2 +1 , h > 0

3、可以证明,对于 h 不等于 0,有 Nh = Fh+3 -1 成立。

4、有n个结点的AVL树的高度不超过 《平衡二叉树(AVL)原理透析和编码解密》

5、在AVL树删除一个结点并做平衡化旋转所需时间为 O(log2n)。

6、 二叉搜索树适合于组织在内存中的较小的索引(或目录)。对于存放在外存中的较大的文件系统,用二叉搜索树来组织索引不太合适。

7、 在文件检索系统中大量使用的是用B_树或B+树做文件索引。

 

 

 

§5 小结

本篇博文已经详细讲解了AVL树数据结构的所有内容,可以说是及其详尽,网络上史无前例,应该可以有一个深入的了解(附件是完成的代码实现)。如果你有任何建议或者批评和补充,请留言指出,不胜感激,更多参考请移步互联网。

 

平衡二叉树(AVL)原理透析和编码解密

 

本文内容框架:

§1 AVL树定义

§2 AVL树平衡化旋转

  §3 AVL树插入删除

§4 AVL树高度分析

§5 小结

 

 

§1 AVL树定义

 

1 AVL树的定义(附件上有完整的AVL树实现)

高度平衡的二叉搜索树

一棵AVL树或者是空树,或者是具有下列性质的二叉搜索树:它的左子树和右子树都是AVL树,且左子树和右子树的高度之差的绝对值不超过1。

《平衡二叉树(AVL)原理透析和编码解密》

高度不平衡的二叉搜索树       高度平衡的二叉搜索树

结点的平衡因子balance (balance factor)

1、每个结点附加一个数字,给出该结点右子树的高度减去左子树的高度所得的高度差。这个数字即为结点的平衡因子balance 。

2、根据AVL树的定义,任一结点的平衡因子只能取 -1,0和 1。

3、如果一个结点的平衡因子的绝对值大于1,则这棵二叉搜索树就失去了平衡,不再是AVL树。

4、如果一棵二叉搜索树是高度平衡的,它就成为 AVL树。如果它有n个结点,其高度可保持在O(log2n),平均搜索长度也可保持在O(log2n)。

AVL树的结点定义

 

Cpp代码  

  1. #ifndef __BIN_TREE_NODE_H__  
  2. #define __BIN_TREE_NODE_H__  
  3.   
  4. #define LH 1                                // 左高  
  5. #define EH 0                                // 等高  
  6. #define RH -1                               // 右高  
  7.   
  8. // 二叉平衡树结点类  
  9. template <class ElemType>  
  10. struct BinAVLTreeNode  
  11. {  
  12. // 数据成员:  
  13.     ElemType data;                          // 数据域  
  14.     int bf;                                 // 结点的平衡因子  
  15.     BinAVLTreeNode<ElemType> *leftChild;  // 左孩子指针域  
  16.     BinAVLTreeNode<ElemType> *rightChild; // 右孩子指针域  
  17.   
  18. //  构造函数:  
  19.     BinAVLTreeNode();                       // 无参数的构造函数   
  20.     BinAVLTreeNode(const ElemType &val,     // 已知数据元素值,平衡因子和指向左右孩子的指针构造一个结点  
  21.         int bFactor = 0,  
  22.         BinAVLTreeNode<ElemType> *lChild = NULL,   
  23.         BinAVLTreeNode<ElemType> *rChild = NULL);  
  24. };  
  25.   
  26. // 二叉平衡树结点类的实现部分  
  27. template <class ElemType>  
  28. BinAVLTreeNode<ElemType>::BinAVLTreeNode()  
  29. // 操作结果:构造一个叶结点  
  30. {  
  31.     bf = 0;                         // 平衡因子  
  32.     leftChild = rightChild = NULL;  // 叶结点左右孩子为空  
  33. }  
  34.   
  35. template <class ElemType>  
  36. BinAVLTreeNode<ElemType>::BinAVLTreeNode(const ElemType &val, int bFactor,   
  37.                                    BinAVLTreeNode<ElemType> *lChild,   
  38.                                    BinAVLTreeNode<ElemType> *rChild)  
  39.   
  40. // 操作结果:构造一个数据域为val,平衡因子为bFactor,左孩子为lChild,右孩子为rChild的结点  
  41. {     
  42.     data = val;                     // 数据元素值  
  43.     bf = bFactor;                   // 平衡因子  
  44.     leftChild = lChild;             // 左孩子  
  45.     rightChild = rChild;            // 右孩子  
  46. }  
  47.   
  48. #endif  

 

AVL树的类定义

 

Cpp代码  

  1. #ifndef __BINNARY_TREE_H__  
  2. #define __BINNARY_TREE_H__  
  3.   
  4. #include “lk_queue.h”                   // 链队列  
  5. #include “lk_stack.h”                   // 链栈  
  6. #include “bin_avl_tree_node.h”          // 二叉平衡树结点类  
  7. enum StatusCode {SUCCESS, FAIL, UNDER_FLOW, OVER_FLOW,RANGE_ERROR, DUPLICATE_ERROR,  
  8.     NOT_PRESENT, ENTRY_INSERTED, ENTRY_FOUND, VISITED, UNVISITED};  
  9. // 二叉平衡树类  
  10. template <class ElemType, class KeyType>  
  11. class BinaryAVLTree  
  12. {  
  13. protected:  
  14. //  二叉平衡树的数据成员:  
  15.     BinAVLTreeNode<ElemType> *root;  
  16.   
  17. //  辅助函数:  
  18.     BinAVLTreeNode<ElemType> *CopyTreeHelp(BinAVLTreeNode<ElemType> *copy); // 复制二叉平衡树  
  19.     void DestroyHelp(BinAVLTreeNode<ElemType> * &r);                      // 销毁以r为根二叉平衡树  
  20.     void PreOrderHelp(BinAVLTreeNode<ElemType> *r, void (*Visit)(const ElemType &)) const;    // 先序遍历  
  21.     void InOrderHelp(BinAVLTreeNode<ElemType> *r, void (*Visit)(const ElemType &)) const// 中序遍历  
  22.     void PostOrderHelp(BinAVLTreeNode<ElemType> *r, void (*Visit)(const ElemType &)) const;   // 后序遍历  
  23.     int HeightHelp(const BinAVLTreeNode<ElemType> *r) const;  // 返回二叉平衡树的高  
  24.     int NodeCountHelp(const BinAVLTreeNode<ElemType> *r) const;// 返回二叉平衡树的结点个数  
  25.     BinAVLTreeNode<ElemType> *ParentHelp(BinAVLTreeNode<ElemType> *r,   
  26.         const BinAVLTreeNode<ElemType> *cur) const;           // 返回cur的双亲  
  27.     BinAVLTreeNode<ElemType> *SearchHelp(const KeyType &key, BinAVLTreeNode<ElemType> *&f) const;     
  28.         // 查找关键字为key的数据元素  
  29.   
  30.     BinAVLTreeNode<ElemType> *SearchHelp(const KeyType &key, BinAVLTreeNode<ElemType> *&f,  
  31.         LinkStack<BinAVLTreeNode<ElemType> *> &s); // 返回指向关键字为key的元素的指针,用f返回其双亲  
  32.     void LeftRotate(BinAVLTreeNode<ElemType> *&subRoot);  
  33.         // 对以subRoot为根的二叉树作左旋处理,处理之后subRoot指向新的树根结点,也就是旋转处理前的右子  
  34.         // 树的根结点  
  35.     void RightRotate(BinAVLTreeNode<ElemType> *&subRoot);  
  36.         // 对以subRoot为根的二叉树作右旋处理,处理之后subRoot指向新的树根结点,也就是旋转处理前的左子  
  37.         // 树的根结点  
  38.     void InsertLeftBalance(BinAVLTreeNode<ElemType> *&subRoot);  
  39.         // 对以subRoot为根的二叉树插入时作左平衡处理,处理后subRoot指向新的树根结点  
  40.     void InsertRightBalance(BinAVLTreeNode<ElemType> *&subRoot);  
  41.         // 对以subRoot为根的二叉树插入时作右平衡处理,处理后subRoot指向新的树根结点  
  42.     void InsertBalance(const ElemType &elem, LinkStack< BinAVLTreeNode<ElemType> *> &s);  
  43.         // 从插入结点elem根据查找路径进行回溯,并作平衡处理  
  44.     void DeleteLeftBalance(BinAVLTreeNode<ElemType> *&subRoot, bool &isShorter);  
  45.         // 对以subRoot为根的二叉树删除时作左平衡处理,处理后subRoot指向新的树根结点  
  46.     void DeleteRightBalance(BinAVLTreeNode<ElemType> *&subRoot, bool &isShorter);  
  47.         // 对以subRoot为根的二叉树删除时作右平衡处理,处理后subRoot指向新的树根结点  
  48.     void DeleteBalance(const KeyType &key, LinkStack<BinAVLTreeNode<ElemType> *> &s);  
  49.         // 从删除结点根据查找路径进行回溯,并作平衡处理  
  50.     void DeleteHelp(const KeyType &key, BinAVLTreeNode<ElemType> *&p,  
  51.         LinkStack< BinAVLTreeNode<ElemType> *> &s);     // 删除p指向的结点  
  52.   
  53. public:  
  54. //  二叉平衡树方法声明及重载编译系统默认方法声明:  
  55.     BinaryAVLTree();                                        // 无参数的构造函数  
  56.     virtual ~BinaryAVLTree();                               // 析构函数  
  57.     BinAVLTreeNode<ElemType> *GetRoot() const;                // 返回二叉平衡树的根  
  58.     bool Empty() const;                                     // 判断二叉平衡树是否为空  
  59.     StatusCode GetElem(BinAVLTreeNode<ElemType> *cur, ElemType &e) const;  
  60.         // 用e返回结点数据元素值  
  61.     StatusCode SetElem(BinAVLTreeNode<ElemType> *cur, const ElemType &e);  
  62.         // 将结cur的值置为e  
  63.     void InOrder(void (*Visit)(const ElemType &)) const;    // 二叉平衡树的中序遍历     
  64.     void PreOrder(void (*Visit)(const ElemType &)) const;   // 二叉平衡树的先序遍历  
  65.     void PostOrder(void (*Visit)(const ElemType &)) const;  // 二叉平衡树的后序遍历  
  66.     void LevelOrder(void (*Visit)(const ElemType &)) const// 二叉平衡树的层次遍历  
  67.     int NodeCount() const;                                  // 求二叉平衡树的结点个数  
  68.     BinAVLTreeNode<ElemType> *Search(const KeyType &key) const;// 查找关键字为key的数据元素  
  69.     bool Insert(const ElemType &e);                         // 插入数据元素e  
  70.     bool Delete(const KeyType &key);                        // 删除关键字为key的数据元素  
  71.     BinAVLTreeNode<ElemType> *LeftChild(const BinAVLTreeNode<ElemType> *cur) const;  
  72.         // 返回二叉平衡树结点cur的左孩子  
  73.     BinAVLTreeNode<ElemType> *RightChild(const BinAVLTreeNode<ElemType> *cur) const;  
  74.         // 返回二叉平衡树结点cur的右孩子  
  75.     BinAVLTreeNode<ElemType> *Parent(const BinAVLTreeNode<ElemType> *cur) const;  
  76.         // 返回二叉平衡树结点cur的双亲  
  77.     int Height() const;                                     // 求二叉平衡树的高  
  78.     BinaryAVLTree(const ElemType &e);                       // 建立以e为根的二叉平衡树  
  79.     BinaryAVLTree(const BinaryAVLTree<ElemType, KeyType> &copy);  // 复制构造函数  
  80.     BinaryAVLTree(BinAVLTreeNode<ElemType> *r);               // 建立以r为根的二叉平衡树  
  81.     BinaryAVLTree<ElemType, KeyType> &operator=(const BinaryAVLTree<ElemType, KeyType>& copy);  // 赋值语句重载  
  82. };  

 

 

 

§2 AVL树平衡化旋转

 

 

2 平衡化旋转

1、如果在一棵平衡的二叉搜索树中插入一个新结点,造成了不平衡。
此时必须调整树的结构,使之平衡化。

2、平衡化旋转有两类:

单旋转 (左旋和右旋)  双旋转 (左平衡和右平衡)

3、每插入一个新结点时,AVL树中相关结点的平衡状态会发生改变。因此,在插入一个新结点后,需要从插入位置沿通向根的路径回溯,检查各结点的平衡因子(左、右子树的高度差)。

4、如果在某一结点发现高度不平衡,停止回溯。

5、从发生不平衡的结点起,沿刚才回溯的路径取直接下两层的结点。

6、 如果这三个结点处于一条直线上,则采用单旋转进行平衡化。单旋转可按其方向分为左单旋转和右单旋转,其中一个是另一个的镜像,其方向与不平衡的形状相关。

7、如果这三个结点处于一条折线上,则采用双旋转进行平衡化。双旋转分为先左后右和先右后左两类。

《平衡二叉树(AVL)原理透析和编码解密》《平衡二叉树(AVL)原理透析和编码解密》《平衡二叉树(AVL)原理透析和编码解密》《平衡二叉树(AVL)原理透析和编码解密》
右单旋转左单旋转左右双旋转右左双旋转

1、左单旋转 (RotateLeft )

《平衡二叉树(AVL)原理透析和编码解密》

(1)如果在子树E中插入一个新结点,该子树高度增1导致结点A的平衡因子变成+2,出现不平衡。

(2)沿插入路径检查三个结点A、C和E。它们处于一条方向为“\”的直线上,需要做左单旋转。

(3)以结点C为旋转轴,让结点A反时针旋转。

左单旋转的算法

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::LeftRotate(BinAVLTreeNode<ElemType> *&subRoot)  
  3. // 操作结果: 对以subRoot为根的二叉树作左旋处理,处理之后subRoot指向新的树根结点,  
  4. //  也就是旋转处理前的右子树的根结点  
  5. {  
  6.     BinAVLTreeNode<ElemType> *ptrRChild;  
  7.     ptrRChild = subRoot->rightChild;         // ptrRChild指向subRoot右孩子  
  8.     subRoot->rightChild = ptrRChild->leftChild;   // ptrRChild的左子树链接为subRoot的右子树  
  9.     ptrRChild->leftChild = subRoot;              // subRoot链接为ptrRChild的左孩子  
  10.     subRoot = ptrRChild;                        // subRoot指向新的根结点  
  11. }  

 

 

2、右单旋转 (RotateRight )

《平衡二叉树(AVL)原理透析和编码解密》

(1)在左子树D上插入新结点使其高度增1,导致结点A的平衡因子增到 -2,造成了不平衡。

(2) 为使树恢复平衡,从A沿插入路径连续取3个结点A、B和D,它们处于一条方向为“/”的直线上,需要做右单旋转。

(3) 以结点B为旋转轴,将结点A顺时针旋转。

右单旋转的算法

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::RightRotate(BinAVLTreeNode<ElemType> *&subRoot)  
  3. // 操作结果: 对以subRoot为根的二叉树作右旋处理,处理之后subRoot指向新的树根结点,  
  4. //  也就是旋转处理前的左子树的根结点  
  5. {  
  6.     BinAVLTreeNode<ElemType> *pLChild;  
  7.     pLChild = subRoot->leftChild;                // pLChild指向subRoot左孩子  
  8.     subRoot->leftChild = pLChild->rightChild; // pLChild的右子树链接为subRoot的左子树  
  9.     pLChild->rightChild = subRoot;               // subRoot链接为pLChild的右孩子  
  10.     subRoot = pLChild;                          // subRoot指向新的根结点  
  11. }  

 

 

3、先左后右双旋转 (RotationLeftRight)

《平衡二叉树(AVL)原理透析和编码解密》

(1)在子树F或G中插入新结点,该子树的高度增1。结点A的平衡因子变为 -2,发生了不平衡。

(2) 从结点A起沿插入路径选取3个结点A、B和E,它们位于一条形如“?”的折线上,因此需要进行先左后右的双旋转。

(3)首先以结点E为旋转轴,将结点B反时针旋转,以E代替原来B的位置,做左单旋转。

(4) 再以结点E为旋转轴,将结点A顺时针旋转,做右单旋转。使之平衡化。

左平衡化的算法

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::InsertLeftBalance(BinAVLTreeNode<ElemType> *&subRoot)  
  3. // 操作结果: 对以subRoot为根的二叉树插入时作左平衡处理,插入结点在subRoot左子树上,处理后  
  4. //  subRoot指向新的树根结点  
  5. {  
  6.     BinAVLTreeNode<ElemType> *ptrLChild, *ptrLRChild;   
  7.     ptrLChild  = subRoot->leftChild; // ptrLChild指向subRoot左孩子  
  8.     switch (ptrLChild->bf)  
  9.     {   // 根据subRoot的左子树的平衡因子作相应的平衡处理  
  10.     case LH:                            // 插入结点在subRoot的左孩子的左子树上,作单右旋处理  
  11.         subRoot->bf = ptrLChild->bf = EH;// 平衡因子都为0  
  12.         RightRotate(subRoot);           // 右旋  
  13.         break;  
  14.     case RH:                            // 插入结点在subRoot的左孩子的右子树上,作先左旋后右旋处理  
  15.         ptrLRChild = ptrLChild->rightChild;// ptrLRChild指向subRoot的左孩子的右子树的根  
  16.         switch (ptrLRChild->bf)  
  17.         {   // 修改subRoot及左孩子的平衡因子  
  18.         case LH:                        // 插入结点在ptrLRChild的左子树上  
  19.             subRoot->bf = RH;  
  20.             ptrLChild->bf = EH;  
  21.             break;  
  22.         case EH:                        // 插入前ptrLRChild为空,ptrLRChild指向插入结点  
  23.             subRoot->bf = ptrLChild->bf = EH;  
  24.             break;  
  25.         case RH:                        // 插入结点在ptrLRChild的左子树上  
  26.             subRoot->bf = EH;  
  27.             ptrLChild->bf = LH;  
  28.             break;  
  29.         }  
  30.         ptrLRChild->bf = 0;  
  31.         LeftRotate(subRoot->leftChild);  // 对subRoot左子树作左旋处理  
  32.         RightRotate(subRoot);           // 对subRoot作右旋处理  
  33.     }  
  34. }  

 

 

4、先右后左双旋转 (RotationRightLeft)

《平衡二叉树(AVL)原理透析和编码解密》

(1)右左双旋转是左右双旋转的镜像。

(2) 在子树F或G中插入新结点,该子树高度增1。结点A的平衡因子变为2,发生了不平衡。

(3) 从结点A起沿插入路径选取3个结点A、C和D,它们位于一条形如“?”的折线上,需要进行先右后左的双旋转。

(4)首先做右单旋转:以结点D为旋转轴,将结点C顺时针旋转,以D代替原来C的位置。

(5) 再做左单旋转:以结点D为旋转轴,将结点A反时针旋转,恢复树的平衡。

右平衡化的算法

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::InsertRightBalance(BinAVLTreeNode<ElemType> *&subRoot)  
  3. // 操作结果: 对以subRoot为根的二叉树插入时作右平衡处理,插入结点在subRoot左子树上,处理后  
  4. //  subRoot指向新的树根结点  
  5. {  
  6.     BinAVLTreeNode<ElemType> *ptrRChild, *ptrRLChild;   
  7.     ptrRChild  = subRoot->rightChild;    // ptrRChild指向subRoot右孩子  
  8.     switch (ptrRChild->bf)  
  9.     {   // 根据subRoot的右子树的平衡因子作相应的平衡处理  
  10.     case RH:                            // 插入结点在subRoot的右孩子的右子树上,作单左旋处理  
  11.         subRoot->bf = ptrRChild->bf = EH;// 平衡因子都为0  
  12.         LeftRotate(subRoot);            // 左旋  
  13.         break;  
  14.     case LH:                            // 插入结点在subRoot的右孩子的左子树上,作先右旋后左旋处理  
  15.         ptrRLChild = ptrRChild->leftChild;// ptrRLChild指向subRoot的右孩子的左子树的根  
  16.         switch (ptrRLChild->bf)  
  17.         {   // 修改subRoot及右孩子的平衡因子  
  18.         case RH:                        // 插入结点在ptrRLChild的右子树上  
  19.             subRoot->bf = LH;  
  20.             ptrRChild->bf = EH;  
  21.             break;  
  22.         case EH:                        // 插入前ptrRLChild为空,ptrRLChild指向插入结点  
  23.             subRoot->bf = ptrRChild->bf = EH;  
  24.             break;  
  25.         case LH:                        // 插入结点在ptrRLChild的左子树上  
  26.             subRoot->bf = EH;  
  27.             ptrRChild->bf = RH;  
  28.             break;  
  29.         }  
  30.         ptrRLChild->bf = 0;  
  31.         RightRotate(subRoot->rightChild);// 对subRoot右子树作右旋处理  
  32.         LeftRotate(subRoot);            // 对subRoot作左旋处理  
  33.     }  
  34. }  

 

 

 

§3 AVL树插入删除

 

3 AVL树的插入和删除

AVL树的插入:

1、在向一棵本来是高度平衡的AVL树中插入一个新结点时,如果树中某个结点的平衡因子的绝对值 |balance| > 1,则出现了不平衡,需要做平衡化处理。

2、在AVL树上定义了重载操作“>>”和“<<”,以及中序遍历的算法。利用这些操作可以执行AVL树的建立和结点数据的输出。

3、 算法从一棵空树开始,通过输入一系列对象的关键码,逐步建立AVL树。在插入新结点时使用了前面所给的算法进行平衡旋转。

例,输入关键码序列为 { 16, 3, 7, 11, 9, 26, 18, 14, 15 },插入和调整过程如下。

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

从空树开始的建树过程

1、下面的算法将通过递归方式将新结点作为叶结点插入并逐层修改各结点的平衡因子。

2、 在发现不平衡时立即执行相应的平衡化旋转操作,使得树中各结点重新平衡化。

3、 在程序中,用变量success记载新结点是否存储分配成功,并用它作为函数的返回值。

4、算法从树的根结点开始,递归向下找插入位置。在找到插入位置(空指针)后,为新结点动态分配存储空间,将它作为叶结点插入,并置success为1,再将taller置为1,以表明插入成功。在退出递归沿插入路径向上返回时做必要的调整。

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::InsertBalance(const ElemType &e,  
  3.     LinkStack<BinAVLTreeNode<ElemType> *> &s)  
  4. // 操作结果: 从插入元素e根据查找路径进行回溯,并作平衡处理  
  5. {  
  6.     bool isTaller = true;  
  7.     while (!s.Empty() && isTaller)  
  8.     {  
  9.         BinAVLTreeNode<ElemType> *ptrCurNode, *ptrParent;  
  10.         s.Pop(ptrCurNode);          // 取出待平衡的结点  
  11.         if (s.Empty())  
  12.         {   // ptrCurNode已为根结点,ptrParent为空  
  13.             ptrParent = NULL;  
  14.         }  
  15.         else  
  16.         {   // ptrCurNode不为根结点,取出双亲ptrParent  
  17.             s.Top(ptrParent);  
  18.         }  
  19.   
  20.         if (e < ptrCurNode->data)  
  21.         {   // e插入在ptrCurNode的左子树上  
  22.             switch (ptrCurNode->bf)  
  23.             {   // 检查ptrCurNode的平衡度  
  24.             case LH:                        // 插入后ptrCurNode->bf=2, 作左平衡处理  
  25.                 if (ptrParent == NULL)  
  26.                 {   // 已回溯到根结点  
  27.                     InsertLeftBalance(ptrCurNode);    
  28.                     root = ptrCurNode;      // 转换后ptrCurNode为新根  
  29.                 }  
  30.                 else if (ptrParent->leftChild == ptrCurNode)  
  31.                 {   // ptrParent左子树作平衡处理  
  32.                     InsertLeftBalance(ptrParent->leftChild);  
  33.                 }  
  34.                 else  
  35.                 {   // ptrParent右子树作平衡处理  
  36.                     InsertLeftBalance(ptrParent->rightChild);  
  37.                 }  
  38.                 isTaller = false;  
  39.                 break;  
  40.             case EH:                    // 插入后ptrCurNode->bf=LH  
  41.                 ptrCurNode->bf = LH;  
  42.                 break;    
  43.             case RH:                    // 插入后ptrCurNode->bf=EH  
  44.                 ptrCurNode->bf = EH;  
  45.                 isTaller = false;  
  46.                 break;  
  47.             }  
  48.         }  
  49.         else  
  50.         {   // e插入在ptrCurNode的右子树上  
  51.             switch (ptrCurNode->bf)  
  52.             {   // 检查ptrCurNode的平衡度  
  53.             case RH:                        // 插入后ptrCurNode->bf=-2, 作右平衡处理  
  54.                 if (ptrParent == NULL)  
  55.                 {   // 已回溯到根结点  
  56.                     InsertRightBalance(ptrCurNode);  
  57.                     root = ptrCurNode;      // 转换后ptrCurNode为新根  
  58.                 }  
  59.                 else if (ptrParent->leftChild == ptrCurNode)  
  60.                 {   // ptrParent左子树作平衡处理  
  61.                     InsertRightBalance(ptrParent->leftChild);  
  62.                 }  
  63.                 else  
  64.                 {   // ptrParent右子树作平衡处理  
  65.                     InsertRightBalance(ptrParent->rightChild);  
  66.                 }  
  67.                 isTaller = false;  
  68.                 break;  
  69.             case EH:                        // 插入后ptrCurNode->bf=RH  
  70.                 ptrCurNode->bf = RH;  
  71.                 break;  
  72.             case LH:                        // 插入后ptrCurNode->bf=EH  
  73.                 ptrCurNode->bf = EH;  
  74.                 isTaller = false;  
  75.                 break;  
  76.             }  
  77.         }  
  78.     }  
  79. }  
  80.   
  81. template <class ElemType, class KeyType>  
  82. bool BinaryAVLTree<ElemType, KeyType>::Insert(const ElemType &e)  
  83. // 操作结果: 插入数据元素e  
  84. {  
  85.     BinAVLTreeNode<ElemType> *f;  
  86.     LinkStack< BinAVLTreeNode<ElemType> *> s;  
  87.     if (SearchHelp(e, f, s) == NULL)  
  88.     {   // 查找失败, 插入成功  
  89.         BinAVLTreeNode<ElemType> *p;      // 插入的新结点  
  90.         p = new BinAVLTreeNode<ElemType>(e);// 生成插入结点  
  91.         p->bf = 0;  
  92.         if (Empty())  
  93.         {   // 空二叉树,新结点为根结点  
  94.             root = p;  
  95.         }  
  96.         else if (e < f->data)  
  97.         {   // e更小,插入结点为f的左孩子  
  98.             f->leftChild = p;  
  99.         }  
  100.         else  
  101.         {   // e更大,插入结点为f的右孩子  
  102.             f->rightChild = p;  
  103.         }  
  104.   
  105.         InsertBalance(e, s);// 插入结点后作平衡处理  
  106.         return true;          
  107.     }  
  108.     else  
  109.     {   // 查找成功, 插入失败  
  110.         return false;  
  111.     }  
  112. }  

 

 

 

AVL树的删除

1、如果被删结点x最多只有一个子女,那么问题比较简单。如果被删结点x有两个子女,首先搜索 x 在中序次序下的直接前驱 y (同样可以找直接后继)。再把 结点y 的内容传送给结点x,现在问题转移到删除结点 y。 把结点y当作被删结点x。

2、 将结点x从树中删去。因为结点x最多有一个子女,我们可以简单地把x的双亲结点中原来指向x的指针改指到这个子女结点;如果结点x没有子女,x双亲结点的相应指针置为NULL。然后将原来以结点x为根的子树的高度减1,

3、必须沿x通向根的路径反向追踪高度的变化对路径上各个结点的影响。

4、 用一个布尔变量 shorter 来指明子树的高度是否被缩短。在每个结点上要做的操作取决于 shorter 的值和结点的 balance,有时还要依赖子女的 balance 。

5、 布尔变量 shorter 的值初始化为True。然后对于从 x 的双亲到根的路径上的各个结点 p,在 shorter 保持为 True 时执行下面的操作。如果 shorter 变成False,算法终止。

6、case 1 : 当前结点p的balance为0。如果它的左子树或右子树被缩短,则它的 balance改为1或-1,同时 shorter 置为False。

7、case 2 : 结点p的balance不为0,且较高的子树被缩短,则p的balance改为0,同时 shorter 置为True。

《平衡二叉树(AVL)原理透析和编码解密》

8、case 3 : 结点p的balance不为0,且较矮的子树又被缩短,则在结点p发生不平衡。需要进行平衡化旋转来恢复平衡。令p的较高的子树的根为 q (该子树未被缩短),根据q的balance ,有如下3种平衡化操作。

9、case 3a : 如果q的balance为0,执行一个单旋转来恢复结点p的平衡,置shorter为False。

 

10、 case 3b : 如果q的balance与p的balance相同,则执行一个单旋转来恢复平衡,结点p和q的balance均改为0,同时置shorter为True。

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

11、case 3c : 如果p与q的balance相反,则执行一个双旋转来恢复平衡,先围绕 q 转再围绕 p 转。新的根结点的balance置为0,其它结点的balance相应处理,同时置shorter为True。

12、 在case 3a, 3b和3c的情形中,旋转的方向取决于是结点p的哪一棵子树被缩短。

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

《平衡二叉树(AVL)原理透析和编码解密》

 

 

Cpp代码  

  1. template <class ElemType, class KeyType>  
  2. void BinaryAVLTree<ElemType, KeyType>::DeleteLeftBalance(BinAVLTreeNode<ElemType> *&  
  3. subRoot, bool &isShorter)  
  4. // 操作结果: 对以subRoot为根的二叉树删除时作左平衡处理, 删除subRoot的左子树上的结点,处  
  5. //  理后subRoot指向新的树根结点  
  6. {  
  7.     BinAVLTreeNode<ElemType> *ptrRChild, *ptrRLChild;   
  8.     ptrRChild  = subRoot->rightChild;        // ptrRChild指向subRoot右孩子  
  9.     switch (ptrRChild->bf)  
  10.     {   // 根据subRoot的右子树的平衡因子作相应的平衡处理  
  11.     case RH:                                // 右高,作单左旋转  
  12.         subRoot->bf = ptrRChild->bf = EH; // 平衡因子都为0  
  13.         LeftRotate(subRoot);                // 左旋  
  14.         isShorter = true;  
  15.         break;  
  16.     case EH:                                // 等高,作单左旋转  
  17.         subRoot->bf = RH;  
  18.         ptrRChild->bf = LH;        
  19.         LeftRotate(subRoot);                // 左旋  
  20.         isShorter = false;  
  21.         break;  
  22.     case LH:                                // 左高,先右旋后左旋  
  23.         ptrRLChild = ptrRChild->leftChild;   // ptrRLChild指向subRoot的右孩子的左子树的根  
  24.         switch (ptrRLChild->bf)  
  25.         {   // 修改subRoot及右孩子的平衡因子  
  26.         case LH:  
  27.             subRoot->bf = EH;  
  28.             ptrRChild->bf = RH;  
  29.             isShorter = true;  
  30.             break;  
  31.         case EH:  
  32.             subRoot->bf = ptrRChild->bf = EH;  
  33.             isShorter = false;  
  34.             break;  
  35.         case RH:  
  36.             subRoot->bf = LH;  
  37.             ptrRChild->bf = EH;  
  38.             isShorter = true;  
  39.             break;  
  40.         }  
  41.         ptrRLChild->bf = 0;  
  42.         RightRotate(subRoot->rightChild);    // 对subRoot右子树作右旋处理  
  43.         LeftRotate(subRoot);                // 对subRoot作左旋处理  
  44.     }  
  45. }  
  46.   
  47. template <class ElemType, class KeyType>  
  48. void BinaryAVLTree<ElemType, KeyType>::DeleteRightBalance(BinAVLTreeNode<ElemType> *  
  49. &subRoot, bool &isShorter)  
  50. // 操作结果: 对以subRoot为根的二叉树删除时作右平衡处理, 删除subRoot的右子树上的结点,处  
  51. //  理后subRoot指向新的树根结点  
  52. {  
  53.     BinAVLTreeNode<ElemType> *ptrLChild, *ptrLRChild;   
  54.     ptrLChild  = subRoot->leftChild; // ptrLChild指向subRoot左孩子  
  55.     switch (ptrLChild->bf)  
  56.     {   // 根据subRoot的左子树的平衡因子作相应的平衡处理  
  57.     case LH:                        // 右高,作单右旋转  
  58.         subRoot->bf = ptrLChild->bf = EH;// 平衡因子都为0  
  59.         RightRotate(subRoot);           // 右旋  
  60.         isShorter = true;  
  61.         break;  
  62.     case EH:                        // 等高,作单右旋转  
  63.         subRoot->bf = LH;  
  64.         ptrLChild->bf = RH;          // 平衡因子都为0  
  65.         RightRotate(subRoot);           // 右旋  
  66.         isShorter = false;  
  67.         break;  
  68.     case RH:                        // 左高,先左旋后右旋  
  69.         ptrLRChild = ptrLChild->rightChild;// ptrLRChild指向subRoot的左孩子的右子树的根  
  70.         switch (ptrLRChild->bf)  
  71.         {   // 修改subRoot及左孩子的平衡因子  
  72.         case LH:  
  73.             subRoot->bf = RH;  
  74.             ptrLChild->bf = EH;  
  75.             isShorter = true;  
  76.             break;  
  77.         case EH:  
  78.             subRoot->bf = ptrLChild->bf = EH;  
  79.             isShorter = false;  
  80.             break;  
  81.         case RH:  
  82.             subRoot->bf = EH;  
  83.             ptrLChild->bf = LH;  
  84.             isShorter = true;  
  85.             break;  
  86.         }  
  87.         ptrLRChild->bf = 0;  
  88.         LeftRotate(subRoot->leftChild);  // 对subRoot左子树作左旋处理  
  89.         RightRotate(subRoot);           // 对subRoot作右旋处理  
  90.     }  
  91. }  
  92.   
  93. template <class ElemType, class KeyType>  
  94. void BinaryAVLTree<ElemType, KeyType>::DeleteBalance(const KeyType &key,   
  95. LinkStack<BinAVLTreeNode<ElemType> *> &s)  
  96. // 操作结果: 从删除结点根据查找路径进行回溯,并作平衡处理  
  97. {  
  98.     bool isShorter = true;  
  99.     while (!s.Empty() && isShorter)  
  100.     {  
  101.         BinAVLTreeNode<ElemType> *ptrCurNode, *ptrParent;  
  102.         s.Pop(ptrCurNode);                  // 取出待平衡的结点  
  103.         if (s.Empty())  
  104.         {   // ptrCurNode已为根结点,ptrParent为空  
  105.             ptrParent = NULL;  
  106.         }  
  107.         else  
  108.         {   // ptrCurNode不为根结点,取出双亲ptrParent  
  109.             s.Top(ptrParent);  
  110.         }  
  111.   
  112.         if (key < ptrCurNode->data)  
  113.         {   // 删除ptrCurNode的左子树上的结点  
  114.             switch (ptrCurNode->bf)  
  115.             {   // 检查ptrCurNode的平衡度  
  116.             case LH:                        // 左高  
  117.                 ptrCurNode->bf = EH;  
  118.                 break;  
  119.             case EH:                        // 等高  
  120.                 ptrCurNode->bf = RH;  
  121.                 isShorter = false;  
  122.                 break;  
  123.             case RH:                        // 右高  
  124.                 if (ptrParent == NULL)  
  125.                 {   // 已回溯到根结点  
  126.                     DeleteLeftBalance(ptrCurNode, isShorter);  
  127.                     root = ptrCurNode;      // 转换后ptrCurNode为新根  
  128.                 }  
  129.                 else if (ptrParent->leftChild == ptrCurNode)  
  130.                 {   // ptrParent左子树作平衡处理  
  131.                     DeleteLeftBalance(ptrParent->leftChild, isShorter);  
  132.                 }  
  133.                 else  
  134.                 {   // ptrParent右子树作平衡处理  
  135.                     DeleteLeftBalance(ptrParent->rightChild, isShorter);  
  136.                 }  
  137.                 break;  
  138.             }  
  139.         }  
  140.         else  
  141.         {   // 删除ptrCurNode的右子树上的结点  
  142.             switch (ptrCurNode->bf)  
  143.             {   // 检查ptrCurNode的平衡度  
  144.             case RH:                        // 右高  
  145.                 ptrCurNode->bf = EH;  
  146.                 break;  
  147.             case EH:                        // 等高  
  148.                 ptrCurNode->bf = LH;  
  149.                 isShorter = false;  
  150.                 break;  
  151.             case LH:                        // 左高  
  152.                 if (ptrParent == NULL)  
  153.                 {   // 已回溯到根结点  
  154.                     DeleteLeftBalance(ptrCurNode, isShorter);  
  155.                     root = ptrCurNode;      // 转换后ptrCurNode为新根  
  156.                 }  
  157.                 else if (ptrParent->leftChild == ptrCurNode)  
  158.                 {   // ptrParent左子树作平衡处理  
  159.                     DeleteLeftBalance(ptrParent->leftChild, isShorter);  
  160.                 }  
  161.                 else  
  162.                 {   // ptrParent右子树作平衡处理  
  163.                     DeleteLeftBalance(ptrParent->rightChild, isShorter);  
  164.                 }  
  165.                 break;  
  166.             }  
  167.         }  
  168.     }  
  169. }  
  170.   
  171. template <class ElemType, class KeyType>  
  172. void BinaryAVLTree<ElemType, KeyType>::DeleteHelp(const KeyType &key,   
  173. BinAVLTreeNode<ElemType> *&p, LinkStack< BinAVLTreeNode<ElemType> *> &s)  
  174. // 操作结果: 删除p指向的结点  
  175. {  
  176.     BinAVLTreeNode<ElemType> *tmpPtr, *tmpF;    
  177.     if (p->leftChild == NULL && p->rightChild == NULL)  
  178.     {   // p为叶结点  
  179.         delete p;  
  180.         p = NULL;  
  181.         DeleteBalance(key, s);  
  182.     }  
  183.     else if (p->leftChild == NULL)  
  184.     {   // p只有左子树为空  
  185.         tmpPtr = p;  
  186.         p = p->rightChild;  
  187.         delete tmpPtr;  
  188.         DeleteBalance(key, s);  
  189.     }  
  190.     else if (p->rightChild == NULL)  
  191.     {   // p只有右子树非空  
  192.         tmpPtr = p;  
  193.         p = p->leftChild;  
  194.         delete tmpPtr;  
  195.         DeleteBalance(key, s);  
  196.     }  
  197.     else  
  198.     {   // p左右子非空  
  199.         tmpF = p;  
  200.         s.Push(tmpF);  
  201.         tmpPtr = p->leftChild;  
  202.         while (tmpPtr->rightChild != NULL)  
  203.         {   // 查找p在中序序列中直接前驱tmpPtr及其双亲tmpF,tmpPtr无右子树为空  
  204.             tmpF = tmpPtr;  
  205.             s.Push(tmpF);  
  206.             tmpPtr = tmpPtr->rightChild;  
  207.         }  
  208.         p->data = tmpPtr->data;// 将tmpPtr指向结点的元素值赋值给tmpF指向结点的元素值  
  209.   
  210.         // 删除tmpPtr指向的结点  
  211.         if (tmpF->rightChild == tmpPtr)  
  212.         {   // 删除tmpF的右孩子  
  213.             DeleteHelp(key, tmpF->rightChild, s);  
  214.         }  
  215.         else  
  216.         {   // 删除tmpF的左孩子  
  217.             DeleteHelp(key, tmpF->leftChild, s);  
  218.         }  
  219.     }  
  220. }  
  221.   
  222. template <class ElemType, class KeyType>  
  223. bool BinaryAVLTree<ElemType, KeyType>::Delete(const KeyType &key)  
  224. // 操作结果: 删除关键字为key的结点  
  225. {  
  226.     BinAVLTreeNode<ElemType> *p, *f;  
  227.     LinkStack< BinAVLTreeNode<ElemType> *> s;  
  228.     p = SearchHelp(key, f, s);  
  229.     if ( p == NULL)  
  230.     {   // 查找失败, 删除失败  
  231.         return false;  
  232.     }  
  233.     else  
  234.     {   // 查找成功, 插入失败  
  235.         if (f == NULL)  
  236.         {   // 被删除结点为根结点  
  237.             DeleteHelp(key, root, s);  
  238.         }  
  239.         else if (key < f->data)  
  240.         {   // key更小,删除f的左孩子  
  241.             DeleteHelp(key, f->leftChild, s);  
  242.         }  
  243.         else  
  244.         {   // key更大,插入f的右孩子  
  245.             DeleteHelp(key, f->rightChild, s);  
  246.         }  
  247.         return true;          
  248.     }  
  249. }  

 

 

§4 AVL树高度分析

 

4 AVL树的高度分析

1、设在新结点插入前AVL树的高度为h,结点个数为n,则插入一个新结点的时间是O(h)。对于AVL树来说,h多大?

2、设 Nh 是高度为 h 的AVL树的最小结点数。根的一棵子树的高度为 h-1,另一棵子树的高度为 h-2,这两棵子树也是高度平衡的。因此有 N-1 = 0 (空树) N0 = 1 (仅有根结点) Nh = Nh-1 + Nh-2 +1 , h > 0

3、可以证明,对于 h 不等于 0,有 Nh = Fh+3 -1 成立。

4、有n个结点的AVL树的高度不超过 《平衡二叉树(AVL)原理透析和编码解密》

5、在AVL树删除一个结点并做平衡化旋转所需时间为 O(log2n)。

6、 二叉搜索树适合于组织在内存中的较小的索引(或目录)。对于存放在外存中的较大的文件系统,用二叉搜索树来组织索引不太合适。

7、 在文件检索系统中大量使用的是用B_树或B+树做文件索引。

 

 

 

§5 小结

本篇博文已经详细讲解了AVL树数据结构的所有内容,可以说是及其详尽,网络上史无前例,应该可以有一个深入的了解(附件是完成的代码实现)。如果你有任何建议或者批评和补充,请留言指出,不胜感激,更多参考请移步互联网。

 

    原文作者:平衡二叉树
    原文地址: https://blog.csdn.net/xiedeacc/article/details/27941027
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞