数据结构实验之查找二:平衡二叉树
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
Hint
Source
xam
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct tree
{
int data,h;
tree *left,*right;
};
int heigh(tree*root)
{
if(root==NULL)return 0;
else return root->h;
}
tree*L_L(tree*root)
{
tree*a=root;
tree*b=root->left;
a->left=b->right;//未来b是要做根的,所以先把b的右儿子找个新家存起来,再进行连接;
b->right=a;
a->h=max(heigh(a->left),heigh(a->right))+1;//这里是重新进行调整,如果没有这些语句,那么之后在调整函数里面对就直接会对返回的root进行调整,从左右高度中选出一个最高的加一,这时候他的左右孩子的高度,包括他自己的高度都是原先的,虽然位置变了,成了那种标准的形式,但是他们的高度还是没有变化的;但是,如果调整了,那么这时候自己的,左右孩子的高度都是标准形式下的高度,最后在插入函数里面调整的时候和这个结果是一样的;
b->h=max(heigh(b->left),heigh(b->right))+1;//这里的调整高度,因为a的左右孩子的指针已经变化了,会根据左右孩子的高度进行调整的;左右孩子都是空,所以自身的高度就是0+1=1;
return b;
}
tree*R_R(tree*root)
{
tree*a=root;
tree*b=root->right;
a->right=b->left;//刚开始,我以为a->h和b->h是一样的是因为这条赋值语句造成的,其实不是,因为,b是root的右孩子,a是root,这个时候a的高度还没有更新那,就进入了这个判断函数了,之后调整完之后再进去插入函数里面进行更新;(更新值是一样的);
b->left=a;
a->h=max(heigh(a->left),heigh(a->right))+1;
b->h=max(heigh(b->left),heigh(b->right))+1;
return b;
}
tree*R_L(tree*root)
{
tree*a=root,*b=a->right,*c=b->left;
a->right=c->left;
b->left=c->right;
c->left=a;
c->right=b;
a->h=max(heigh(a->left),heigh(a->right))+1;
b->h=max(heigh(b->left),heigh(b->right))+1;
c->h=max(heigh(c->left),heigh(c->right))+1;
return c;
}
tree*L_R(tree*root)
{
tree*a=root,*b=a->left,*c=b->right;
b->right=c->left;//未来C是要做根的,先把c的左右儿子找个新家存起来,但是要注意大小
a->left=c->right;
c->left=b;
c->right=a;
a->h=max(heigh(a->left),heigh(a->right))+1;
b->h=max(heigh(b->left),heigh(b->right))+1;
c->h=max(heigh(c->left),heigh(c->right))+1;
return c;
}
tree*insert_x(tree*root,int x)
{
if(root==NULL)
{
root=new tree;
root->h=0;
root->data=x;
root->left=root->right=NULL;
}
else
{
if(x<root->data)
{
root->left=insert_x(root->left,x);
if(heigh(root->left)-heigh(root->right)==2)
{
if(x<(root->left)->data)
{
root=L_L(root);
}
else
{
root=L_R(root);
}
}
}
else
{
root->right=insert_x(root->right,x);
if(heigh(root->left)-heigh(root->right)==-2)
{
if(x>(root->right)->data)
{
root=R_R(root);
}
else root=R_L(root);
}
}
}
root->h=max(heigh(root->left),heigh(root->right))+1;//当调整完之后到了这里就不用再调整了,因为已经调整完了;调整结果是相同的;但是如果不需要进入调整函数,那这时候的高度都是要更新的;
return root;
}
int main()
{
int n;
scanf("%d",&n);
tree*root;
root=NULL;
for(int i=1;i<=n;i++)
{
int t;
scanf("%d",&t);
root=insert_x(root,t);
}
printf("%d\n",root->data);
return 0;
}