平衡搜索树-AVL树

来源:互联网 发布:内网访问阿里云 编辑:程序博客网 时间:2024/05/16 04:22
# include<iostream>using namespace std;template<class K,class V>struct AVLTreeNode{AVLTreeNode *_parent;AVLTreeNode *_right;AVLTreeNode *_left;K key;V value;int _bf;//定义平衡因子AVLTreeNode(const K&key,const V&value):_parent(NULL), _right(NULL), _left(NULL), _key(key ), _value(value), _bf(0){}};template<class K,class V>class AVLTree{typedef AVLTreeNode<K,V> Node;private:Node *_root;public:AVLTree():_root(NULL){}bool Insert(const K&key, const V&value){//将节点插成二叉搜索树if (_root == NULL){_root = new Node(key, value);return true;}Node *cur =_root;Node *parent = NULL;while (cur){if (key > cur->key){ parent = cur;cur = cur->_right;}else if (key<cur->key){parent = cur;cur = cur->_left;}else {return false;}cur = new Node(key, value);if (key>parent->key){parent->_right = cur;cur->_parent = parent;}else{parent->_left = cur;cur->_parent = parent;}}//调整平衡因子bool IsRotate = false;while (parent){if (cur == parent->_left){parent->_bf--;}else{parent->_bf++;}if (parent->_bf == 0)//程序能进入这里,这说明插入节点失败,不用调整平衡直接退出{break;}else if (parent->_bf == 1 || parent->_bf == -1){cur = parent;parent = parent->_parent;}else//parent为2或-2的情况{IsRotate = true;if (parent->_bf == 2){if (cur->_bf == 1){RotateL(parent);//左单旋转}if (cur->_bf == -1){RotateRL(parent);//先右后左双旋转}}else//也就是parent->_bf==-2的情况{if (cur->_bf == -1){RotateR(parent);//右单旋转}if (cur->_bf == 1){RotateLR(parent);//先左后右双旋转}}break;}}if (IsRotate){Node* GrandParent = parent->_parent;if (GrandParent == NULL){_root = parent;}else{if (parent->_key < GrandParent->_key){GrandParent->_left = parent;}else{GrandParent->_right = parent;}}}return true;}};

0 0