结构
template<typename T>
struct AVLNode{
T data;
int height;
AVLNode* lchild, *rchild;
AVLNode(T dt, AVLNode* l, AVLNode* r):data(dt),lchild(l),rchild(r){}
};
template<typename T>
class AVLTree{
public:
AVLTree(){
root = nullptr;
}
~AVLTree(){
Destory(root);
}
void Insert(T data){
_insert(root, data);
}
bool Search(T data){
//return _searchRecursion(root,data);
return _searchNotRecursion(root, data);
}
bool DeleteData(T data){
return _deleteData(root, data);
}
AVLNode<T>* Left_Rotation(AVLNode<T>* pRoot); // 左旋
AVLNode<T>* Right_Rotation(AVLNode<T>* pRoot); // 右旋
AVLNode<T>* LR_Rotation(AVLNode<T>* pRoot); // 先左旋后右旋
AVLNode<T>* RL_Rotation(AVLNode<T>* pRoot); // 先右旋后左旋
private:
AVLNode<T>* root;
void _insert(AVLNode<T>* pRoot, T data);
bool _searchRecursion(AVLNode<T>* pRoot, T data); //递归搜索
bool _searchNotRecursion(AVLNode<T>* pRoot, T data);//非递归搜索
void Destory(AVLNode<T>* pRoot);
bool _deleteData(AVLNode<T>* pRoot, T data);
};
四种旋转场景
通过比较左右子树的高度差(即平衡因子)来反映是否平衡
?
template<typename T>
AVLNode<T>* AVLTree<T>::Left_Rotation(AVLNode<T>* pRoot)
{
AVLNode<T>* p = pRoot->rchild;
pRoot->rchild = p->lchild;
p->lchild = pRoot;
pRoot->height = max(pRoot->lchild->height, pRoot->rchild->height)+1;
p->height = max(p->lchild->height, p->rchild->height)+1;
return p;
}
template<typename T>
AVLNode<T>* AVLTree<T>::Right_Rotation(AVLNode<T>* pRoot)
{
AVLNode<T>* p = pRoot->lchild;
pRoot->lchild = p->rchild;
p->rchild = pRoot;
pRoot->height = max(pRoot->lchild->height, pRoot->rchild->height)+1;
p->height = max(p->lchild->height, p->rchild->height)+1;
return p;
}
template<typename T>
AVLNode<T>* AVLTree<T>::LR_Rotation(AVLNode<T>* pRoot)
{
Left_Rotation(pRoot->rchild);
Right_Rotation(pRoot);
return pRoot->rchild;
}
template<typename T>
AVLNode<T>* AVLTree<T>::RL_Rotation(AVLNode<T>* pRoot)
{
Right_Rotation(pRoot->lchild);
Left_Rotation(pRoot);
return pRoot->lchild;
}
|