数据结构--平衡二叉树的插入详解

来源:互联网 发布:计算机网络就业 知乎 编辑:程序博客网 时间:2024/05/06 15:03

平衡二叉树(AVLTree):

平衡二叉树具有以下性质:

1.它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。

2.这个方案很好的解决了二叉查找树退化成链表的问题,把插入,查找,删除的时间复杂度最好情况和最坏情况都维持在O(logN)。

3.频繁旋转会使插入和删除牺牲掉O(logN)左右的时间,不过相对二叉查找树来说,时间上稳定了很多。

 

平衡二叉树的插入:

当插入后,二叉树结点右侧的高度与左侧高度之差的绝对值为小于等于1的时候,我们就认为他为平衡的,否则,我们应该调整。

调整:

单旋转:

双旋转:



#include <iostream>using namespace std;template<class K,class V>struct AVLTreeNode{AVLTreeNode(const K&  key,const V& value):_key(key), _value(value){}AVLTreeNode<K, V>* _pLeft;AVLTreeNode<K, V>* _pRight;AVLTreeNode<K, V>* _pParents;K _key;V _value;int _bf;//平衡因子};template<class K, class V>class AVLTree{typedef AVLTreeNode<K, V> Node;public:AVLTree():_pRoot(NULL){}bool Insert(const K& key,const V& value){//判断头结点if (_pRoot == NULL){_pRoot = new Node(key, value);return true;}//如果头不为空Node * pCur = _pRoot;Node * pParent = NULL;while (pCur){if (pCur->_key < key){pParent = pCur;pCur = pCur->_pRight;}else if (pCur->_key > key){pParent = pCur;pCur = pCur->_pLeft;}}//插入并链接pCur = new Node(key,value);if (key < pParent->_key)pParent->_pLeft = pCur;else if (key > pParent->_key)pParent->_pRight = pCur;pCur->_pParents = pParent;//更新平衡因子while (pCur){if (pParent->_pRight == pCur)pParent->_bf++;elsepParent->_bf--;//当父亲结点的平衡因子为0的时候 就更新完了if (pParent->_bf == 0)return true;else if (pParent->_bf == -1 || pParent->_bf == 1){pCur = pParent;pParent = pParent->_pParents;}else{//应该调节平衡因子if (pParent->_bf == -2){if (pCur->_bf == -1)_RotateR(pParent);else_RotateLR(pParent);}else{if (pCur->_bf == 1)_RotateL(pParent);else_RotateRL(pParent);}}}return true;}private://右单旋void _RotateR(Node* Parent){Node* SubL = Parent->_pLeft;Node* SubLR = SubL->_pRight;Parent->_pLeft = SubLR;if (SubLR)SubLR->_pParents = Parent;SubL->_pRight = Parent;SubL->_pParents = Parent->_pParents;Node* _pPparent = Parent->_pParents;Parent->_pParents = SubL;if (_pPparent == NULL)_pRoot = SubL;if (_pPparent->_pLeft == Parent)_pPparent->_pLeft = SubL;else_pPparent->_pRight = SubL;SubL->_bf = Parent->_bf = 0;}//左单旋void _RotateL(Node* Parent){Node* SubR = Parent->_pRight;Node* SubRL = SubR->_pLeft;Parent->_pRight = SubRL;if (SubRL)SubRL->_pParents = Parent;SubR->_pLeft = Parent;SubR->_pParents = Parent->_pParents;Node* _pPparent = Parent->_pParents;Parent->_pParents = SubR;if (_pPparent == NULL)_pRoot = SubR;if (_pPparent->_pLeft == Parent)_pPparent->_pLeft = SubR;else_pPparent->_pRight = SubR;SubR->_bf = Parent->_bf = 0;}//左右旋void _RotateLR(Node* Parent){int bs = Parent->_pLeft->_pRight->_bf;_RotateL(Parent->_pLeft);_RotateR(Parent);if (bs == 1){Parent->_key = 0;Parent->_pLeft->_key = -1;}else if (bs == -1){Parent->_bf = 1;Parent->_pLeft->_key = 0;}}//右左旋void _RotateRL(Node* Parent){int bs = Parent->_pRight->_pLeft->_bf;_RotateR(Parent->_pRight);_RotateL(Parent);if (bs == 1){Parent->_key = -1;Parent->_pRight->_key = 0;}else if (bs == -1){Parent->_bf = 0;Parent->_pRight->_key = 1;}}private:Node * _pRoot;};

 

0 0
原创粉丝点击