数据结构实验之查找二:平衡二叉树
Time Limit: 400MS Memory Limit: 65536KB
Problem Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Example Input
5
88 70 61 96 120
Example Output
70
Hint
Author
xam
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
int h;
struct node *lchild,*rchild;
};
int MyMax(int x,int y)
{
return x>y?x:y;
}
int deep(struct node *t)
{
if(t==NULL)return -1;
else return t->h;
}
struct node *LL(struct node *t)
{
struct node *q;
q = t -> lchild;
t -> lchild = q -> rchild;
q -> rchild = t;
q -> h = MyMax(deep(q->lchild),deep(q->rchild)) + 1;
t -> h = MyMax(deep(t->lchild),deep(t->rchild)) + 1;
return q;
}
struct node *RR(struct node *t)
{
struct node *q;
q = t -> rchild;
t -> rchild = q -> lchild;
q -> lchild = t;
q -> h = MyMax(deep(q->lchild),deep(q->rchild)) + 1;
t -> h = MyMax(deep(t->lchild),deep(t->rchild)) + 1;
return q;
}
struct node *LR(struct node *t)
{
struct node *q,*tail;
q = t -> lchild;
tail = q -> rchild;
q -> rchild = tail -> lchild;
tail -> lchild = q;
t->lchild = tail -> rchild;
tail -> rchild = t;
tail -> h = MyMax(deep(tail->lchild),deep(tail->rchild)) + 1;
q -> h = MyMax(deep(q->lchild),deep(q->rchild)) + 1;
t -> h = MyMax(deep(t->lchild),deep(t->rchild)) + 1;
return tail;
}
//或者用
//struct node *LR(struct node *t)
//{
//t->lchild = RR(t->lchild);//先做左旋
//return LL(t);//在做右旋
//}
struct node *RL(struct node *t)
{
struct node *q,*tail;
q = t -> rchild;
tail = q -> lchild;
q -> lchild = tail -> rchild;
tail -> rchild = q;
t -> rchild = tail -> lchild;
tail -> lchild = t;
tail -> h = MyMax(deep(tail->lchild),deep(tail->rchild)) + 1;
q -> h = MyMax(deep(q->lchild),deep(q->rchild)) + 1;
t -> h = MyMax(deep(t->lchild),deep(t->rchild)) + 1;
return tail;
}
//struct node *RL(struct node *t)
//{
// t->rchild = LL(t->rchild);//先做右旋
// return RR(t);//在做左旋
//}
struct node *creat(struct node *root,int x)
{
if(root==NULL)
{
root = (struct node *)malloc(sizeof(struct node));
root -> data = x;
root -> h = 0;
root -> lchild = root -> rchild = NULL;
}
else if(x < root->data)
{
root -> lchild = creat(root -> lchild,x);
if(deep(root->lchild) - deep(root->rchild) > 1)
{
if(x < root->lchild->data)
root = LL(root);
else root = LR(root);
}
}
else if(x > root->data)
{
root -> rchild = creat(root->rchild,x);
if(deep(root->rchild) - deep(root->lchild) > 1)
{
if(x < root->rchild->data)
root = RL(root);
else root = RR(root);
}
}
root -> h = MyMax(deep(root->lchild),deep(root->rchild)) + 1;
return root;
}
int main()
{
struct node *root;
root = NULL;
int n,i;
scanf("%d",&n);
for(i = 0;i < n;i++)
{
int x;
scanf("%d",&x);
root = creat(root,x);
}
printf("%d\n",root->data);
return 0;
}