北邮oj 平衡树

1 篇文章 0 订阅
1 篇文章 0 订阅

题目要求

输入:一串字符被逗号隔开,注意最后一位是逗号
输出:前序遍历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的变化和平衡因子的变化
        一些初始化必须做好,否则程序可能出现错误
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值