头文件 AVLtree.h :
#ifndef AVLTREE_H
#define AVLTREE_H
template<typename Comparable>
class AVLtree{
public:
AVLtree(){
root=NULL;
}
AVLtree(const AVLtree & rhs){
this->root=rhs.root;
}
~AVLtree(){
makeEmpty();
}
void makeEmpty(){
makeEmpty(root);
}
void insert(const Comparable & x){
insert(x,root);
}
void printTree() const{
printTree(root);
}
private:
struct AvlNode{
Comparable element;
AvlNode *left;
AvlNode *right;
int height;
AvlNode(const Comparable & theElement, AvlNode *lt, AvlNode *rt, int h=0)
:element(theElement),left(lt),right(rt),height(h){}
};
AVLtree<Comparable>::AvlNode *root;
int max(Comparable a,Comparable b){
return a>b ? a : b;
}
//清空树的操作
void makeEmpty( AVLtree<Comparable>::AvlNode * & t){
//递归形式
if(t!=NULL){
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
}
t=NULL;
}
//计算AVL结点高度的函数
int height(AVLtree<Comparable>::AvlNode * t) const{
return t==NULL ? -1 : t->height;
}
//向AVl树的插入操作
void insert(const Comparable & x, AVLtree<Comparable>::AvlNode* & t){
if(t==NULL)
t=new AVLtree<Comparable>::AvlNode(x,NULL,NULL);
else if(x<t->element){
insert(x,t->left);
if(height(t->left)-height(t->right)==2){
if(x<t->left->element)
rotateWithLeftChild(t);
else
doubleWithLeftChild(t);
}
}
else if(t->element<x){
insert(x,t->right);
if(height(t->right)-height(t->left)==2){
if(t->right->element<x)
rotateWithRightChild(t);
else
doubleWithRightChild(t);
}
}
else
;//do nothing.
t->height=max(height(t->left),height(t->right)) + 1; //更新结点t的高度
}
//左子树做单旋转
void rotateWithLeftChild(AVLtree<Comparable>::AvlNode * & k2){
AVLtree<Comparable>::AvlNode *k1=k2->left;
k2->left=k1->right;
k1->right=k2;
k2->height=max( height(k2->left),height(k2->right) ) + 1;
k1->height=max( height(k1->left), k2->height ) + 1;
k2=k1;
}
//右子树做单旋转
void rotateWithRightChild(AVLtree<Comparable>::AvlNode * & k2){
AVLtree<Comparable>::AvlNode *k1=k2->right;
k2->right=k1->left;
k1->left=k2;
k2->height=max( height(k2->left),height(k2->right) ) + 1;
k1->height=max( height(k1->right), k2->height ) + 1;
k2=k1;
}
//左子树做双旋转
void doubleWithLeftChild(AVLtree<Comparable>::AvlNode * & k3){
rotateWithRightChild(k3->left);
rotateWithLeftChild(k3);
}
//右子树做双旋转
void doubleWithRightChild(AVLtree<Comparable>::AvlNode * & k3){
rotateWithLeftChild(k3->right);
rotateWithRightChild(k3);
}
void printTree(AVLtree<Comparable>::AvlNode *t) const{
//前序遍历
/* if(t!=NULL){
cout<<t->element<<" ";
// cout<<"!!"<<t->height<<" ";
printTree(t->left);
printTree(t->right);
}*/
//中序遍历
if(t!=NULL){
printTree(t->left);
cout<<t->element<<" ";
// cout<<"!!"<<t->height<<" ";
printTree(t->right);
}
/* //后序遍历
if(t){
printTree(t->left);
printTree(t->right);
cout<<t->element<<" ";
}*/
}
};
#endif
主函数 main.cpp :
#include<iostream>
using namespace std;
#include"AVLtree.h"
int main(){
AVLtree<int> Atree;
int x;
while(cin>>x,x!=0){
Atree.insert(x);
}
Atree.printTree();
cout<<endl;
return 0;
}
运行结果:
input:
3 2 1 4 5 6 7 16 15 14 13 12 11 10 8 9 0
output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Press any key to continue