在此,主要介绍,AVL的创建,仅仅用层次遍历验证AVL树创建的正确性,想要详细了解,先序,中序,后序和层次遍历,请参考我之前的发布的一篇介绍遍历的博客---- https://blog.csdn.net/kz_java/article/details/88358491 建树->先序-中序-后序-层次遍历
#include<stdio.h>
#include<queue>
using namespace std;
//AVL 19-3-10
int i,N,num[10005];
struct node{
int data,height;
node* lchild,*rchild;
};
node* newNode(int x){
node* Node=new node;
Node->data=x;
Node->height=1;
Node->lchild=Node->rchild=NULL;
return Node;
}
int getHeight(node*root){
if(root==NULL)
return 0;
return root->height;
}
int getBF(node*root){
return getHeight(root->lchild)-getHeight(root->rchild);
}
void updataHeight(node*root){
root->height=max(getHeight(root->lchild),getHeight(root->rchild))+1;
}
void R(node*&root){
node*temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
updataHeight(root);
updataHeight(temp);
root=temp;
}
void L(node*&root){
node*temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
updataHeight(root);
updataHeight(temp);
root=temp;
}
void insert(node*&root,int x){
if(root==NULL){
root=newNode(x);
return;
}
if(x<root->data){
insert(root->lchild,x);
updataHeight(root);
if(getBF(root)==2){
if(getBF(root->lchild)==1){
R(root);
}else if(getBF(root->lchild)==-1){
L(root->lchild);
R(root);
}
}
}else{
insert(root->rchild,x);
updataHeight(root);
if(getBF(root)==2){
if(getBF(root->lchild)==1){
L(root);
}else if(getBF(root->rchild)==-1){
R(root->rchild);
L(root);
}
}
}
}
node* Create(int data[],int len){
node*root=NULL;
for(int i=0;i<len;i++)
insert(root,data[i]);
return root;
}
void LayerOrder(node*root){
queue<node*>q;
q.push(root);
while(!q.empty()){
node*now=q.front();
q.pop();
printf("%d ",now->data);
if(now->lchild)
q.push(now->lchild);
if(now->rchild)
q.push(now->rchild);
}
}
int main(){
scanf("%d",&N);
for(i=0;i<N;i++)
scanf("%d",num+i);
node*root=Create(num,N);
LayerOrder(root);
return 0;
}