数据结构实验之查找二:平衡二叉树
Time Limit: 400MS Memory limit: 65536K
题目描述
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
输入
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
输出
输出平衡二叉树的树根。
示例输入
5
88 70 61 96 120
示例输出
70
提示
来源
xam
示例程序
http://blog.chinaunix.net/uid-24948645-id-3913917.html这是一个网址的链接,里面关于平衡二叉树的讲解比较清晰
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
int data;
int high;
struct node *lchild,*rchild;
} tree;
int max(int x,int y)
{
if(x > y)
return x;
else
return y;
}
int deep(tree *root)
{
if(!root)
return -1;
else
return root->high;
}
tree *LL(tree *root)
{
tree *p;
p = root->lchild;
root->lchild = p->rchild;
p->rchild = root;
p->high = max(deep(p->lchild),deep(p->rchild))+1;
root->high = max(deep(root->lchild),deep(root->rchild))+1;
return p;
}
tree *RR(tree *root)
{
tree *p;
p = root->rchild;
root->rchild = p->lchild;
p->lchild = root;
p->high = max(deep(p->lchild),deep(p->rchild))+1;
root->high = max(deep(root->lchild),deep(root->rchild))+1;
return p;
}
tree *RL(tree *root)
{
root->lchild = RR(root->lchild);
return LL(root);
}
tree *LR(tree *root)
{
root->rchild = LL(root->rchild);
return RR(root);
}
tree *creat(tree *root,int key)
{
if(!root)
{
root = (tree *)malloc(sizeof(tree));
root->lchild = root->rchild=NULL;
root->data = key;
root->high = 0;
}
else if(root->data > key)
{
root->lchild = creat(root->lchild,key);
if(deep(root->lchild) - deep(root->rchild)>1)
{
if(root->lchild->data > key)
root = LL(root);
else
root = RL(root);
}
}
else if(root->data < key)
{
root->rchild = creat(root->rchild,key);
if(deep(root->rchild) - deep(root->lchild)>1)
{
if(root->rchild->data < key)
root = RR(root);
else
root = LR(root);
}
}
root->high = max(deep(root->lchild),deep(root->rchild))+1;
return root;
}
int main()
{
int n;
int num;
scanf("%d",&n);
tree *root;
root = NULL;
for(int i = 0; i < n; i++)
{
scanf("%d",&num);
root = creat(root,num);
}
printf("%d\n",root->data);
return 0;
}