数据结构实验之查找二:平衡二叉树
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 <iostream>
#include<stdio.h>
#include<stdlib.h>
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*R_R(tree*root)
{
tree*a=root,*b=root->right;
a->right=b->left;
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*L_L(tree*root)
{
tree*a=root,*b=root->left;
a->left=b->right;
b->right=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=root->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=root->left,*c=b->right;
b->right=c->left;
a->left=c->right;
c->right=a;
c->left=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*invert(tree*root,int x)
{
if(root==NULL)
{
root=new tree;
root->data=x;
root->h=0;
root->left=NULL;
root->right=NULL;
}
else
{
if(x<root->data)
{
root->left=invert(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=invert(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;
tree*root;
root=NULL;
scanf("%d",&n);
while(n--)
{
int x;
scanf("%d",&x);
root=invert(root,x);
}
printf("%d\n",root->data);
return 0;
}