数据结构实验之查找二:平衡二叉树
Time Limit: 400 ms Memory Limit: 65536 KiB
Problem Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Sample Input
5 88 70 61 96 120
Sample Output
70
C语言实现,代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct tree
{
int data, h;
struct tree *l, *r;
} *root;
int height(struct tree *root)
{
if(!root) return 0;
else return root->h;
}
struct tree *RR(struct tree *root)
{
struct tree *a = root, *b = root->r;
a->r = b->l;
b->l = a;
a->h = height(a->l) > height(a->r) ? height(a->l) + 1 : height(a->r) + 1;
b->h = height(b->l) > height(b->r) ? height(b->l) + 1 : height(b->r) + 1;
return b;
};
struct tree *LL(struct tree *root)
{
struct tree *a = root, *b = root->l;
a->l = b->r;
b->r = a;
a->h = height(a->l) > height(a->r) ? height(a->l) + 1 : height(a->r) + 1;
b->h = height(b->l) > height(b->r) ? height(b->l) + 1 : height(b->r) + 1;
return b;
};
struct tree *LR(struct tree *root)
{
root->l = RR(root->l); // 先左
return LL(root); // 后右
};
struct tree *RL(struct tree *root)
{
root->r = LL(root->r); // 先右
return RR(root); // 后左
};
struct tree *Insert(struct tree *root, int x)
{
if(!root)
{
root = (struct tree *)malloc(sizeof(struct tree));
root->data = x;
root->h = 0;
root->l = NULL;
root->r = NULL;
}
else
{
if(x < root->data)
{
root->l = Insert(root->l, x);
if(height(root->l) - height(root->r) == 2)
{
if(x < root->l->data)
root = LL(root);
else
root = LR(root);
}
}
else
{
root->r = Insert(root->r, x);
if(height(root->l) - height(root->r) == -2)
{
if(x > root->r->data)
root = RR(root);
else
root = RL(root);
}
}
}
root->h = height(root->l) > height(root->r) ? height(root->l) + 1: height(root->r) + 1;
return root;
};
int main()
{
int n;
struct tree *root;
root = NULL;
scanf("%d", &n);
while(n--)
{
int x;
scanf("%d", &x);
root = Insert(root, x);
}
printf("%d\n", root->data);
return 0;
}