题目要求
输入:一串字符被逗号隔开,注意最后一位是逗号
输出:前序遍历AVL树,用逗号隔开
代码
#include<stdio.h>
#include<stdlib.h>
#define Max 50
typedef struct tnode
{
int data;
int height;
struct tnode*lchild;
struct tnode*rchild;
}*tree,Tree;
int getheight(tree root)
{
if(root==NULL)return 0;
else return root->height;
}
int BalanceNumber(tree root)
{
if(root==NULL)return 0;
else return (getheight(root->lchild)-getheight(root->rchild));
}
int Ismax(int a, int b)
{
return (a>b)?a:b;
}
tree ll(tree root)
{
tree temp=root->lchild;
root->lchild=temp->rchild;
temp->rchild=root;
root->height=Ismax(getheight(root->lchild),getheight(root->rchild))+1;
temp->height=Ismax(getheight(temp->lchild),getheight(temp->rchild))+1;
return temp;
}
tree rr(tree root)
{
tree temp=root->rchild;
root->rchild=temp->lchild;
temp->lchild=root;
root->height=Ismax(getheight(root->lchild),getheight(root->rchild))+1;
temp->height=Ismax(getheight(temp->lchild),getheight(temp->rchild))+1;
return temp;
}
tree Insert(tree root,int x)//AVL树
{
if(root==NULL)
{
root=(tree)malloc(sizeof(Tree));
root->data=x;
root->height=1;
root->lchild=NULL;
root->rchild=NULL;
return root;
}
if(x>root->data) root->rchild=Insert(root->rchild,x);
else if(x<root->data) root->lchild=Insert(root->lchild,x);
else return root;
//高度问题有误差
root->height=1+Ismax(getheight(root->lchild),getheight(root->rchild));
int balance=BalanceNumber(root);
if(balance>1 && x<root->lchild->data)//ll
{
return ll(root);
}
else if(balance<-1 && x>root->rchild->data)//rr
{
return rr(root);
}
else if(balance>1 && x>root->lchild->data)//lr
{
root->lchild=rr(root->lchild);
return ll(root);
}
else if(balance<-1 && x<root->rchild->data)//rl
{
root->rchild=ll(root->rchild);
return rr(root);
}
return root;
}
void Preorder(tree root)
{
if(root!=NULL)
{
printf("%d,",root->data);
Preorder(root->lchild);
Preorder(root->rchild);
}
}
int main()
{
tree root=NULL;
int i=0,j,top=-1,topa=-1,stack[Max],a[Max];
char c[Max];
scanf("%s",c);
while(c[i]!='\0')
{
if(c[i]!=',')
{
stack[++top]=c[i]-'0';
}
else if(c[i]==',')
{
a[++topa]=0,j=1;
while(top!=-1)
{
a[topa]+=stack[top--]*j;
j*=10;
}
}
i++;
}
for(i=0;i<=topa;i++)
{
root=Insert(root,a[i]);
}
Preorder(root);
return 0;
}
分析过程
题目重点在于[AVL树]的构建,Insert函数为具体操作过程
答题者应当把重点放在递归函数的逻辑以及一些细节上
注意height的变化和平衡因子的变化
一些初始化必须做好,否则程序可能出现错误