题目描述
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
输入
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
输出
输出平衡二叉树的树根。
示例输入
5 88 70 61 96 120
示例输出
70
提示
<span style="font-size:14px;">#include<iostream>
#include<cstdlib>
using namespace std;
struct node
{
int data;//数据
int dp;//平衡因子
struct node *lchild,*rchild;
};
int deep(struct node *root) //返回树的深度
{
if(!root)
return -1;
else
return root->dp;
}
struct node *LL(struct node *root) //对LL型直接在不平衡点进行坐旋转
{
struct node *tail;
tail=root->lchild;
root->lchild=tail->rchild;
tail->rchild=root;
tail->dp=max(deep(tail->lchild),deep(tail->rchild))+1;//节点位置变化,要更新节点的高度
root->dp=max(deep(root->lchild),deep(root->rchild))+1;
return tail;
}
struct node *RR(struct node *root)
{
struct node *tail;
tail=root->rchild;
root->rchild=tail->lchild;
tail->lchild=root;
tail->dp=max(deep(tail->lchild),deep(tail->rchild))+1;
root->dp=max(deep(root->lchild),deep(root->rchild))+1;
return tail;
}
struct node *LR(struct node *root)
{
root->rchild=LL(root->rchild);//在不平衡点P的左儿子处进行右旋转
return RR(root);//在不平衡点P处进行左旋转并且返回新的值
}
struct node *RL(struct node *root)
{
root->lchild=RR(root->lchild);//在不平衡点P的右儿子处进行左旋转
return LL(root);//在不平衡点P处进行坐旋转并且返回新的根
}
struct node *creat(struct node *root,int n)
{
if(root==NULL)//待插入的值赋给新的节点
{
root=(struct node *)malloc(sizeof(struct node));
root->lchild=NULL;
root->rchild=NULL;
root->data=n;
root->dp=0;
}
else if(n<root->data) //如果要插入的值小于根节点的值,则插入到左子树中
{
root->lchild=creat(root->lchild,n);
if(deep(root->lchild)-deep(root->rchild)>1)//该树出现不平衡
{
if(n<root->lchild->data)//若待插入的值放到了左儿子的左子树上就单旋转
root=LL(root);
else //反之,双旋转
root=LR(root);
}
}
else if(n>root->data)
{
root->rchild=creat(root->rchild,n);
if(deep(root->rchild)-deep(root->lchild)>1)
{
if(n>root->rchild->data)
root=RR(root);
else
root=RL(root);
}
}
root->dp=max(deep(root->lchild),deep(root->rchild))+1;//更新数的高度
return root;
}
int main()
{
struct node *root=NULL;
int n,a;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a;
root=creat(root,a);
}
cout<<root->data<<endl;
return 0;
}
</span>