数据结构实验之查找二:平衡二叉树
Time Limit: 400MS
Memory Limit: 65536KB
Problem Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Example Input
5 88 70 61 96 120
Example Output
70
Hint
Author
xam
参考博客:点击打开链接
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
int deep;
struct node *l, *r;
};
node *root;
int depth(node *p)//返回树的深度
{
if(!p)
return -1;
else
return p->deep;
}
void LL(node *&p)//左旋
{
node *q;
q = p->l;
p->l = q->r;
q->r = p;
p->deep = max(depth(p->r), depth(p->l)) + 1;//现在已经成为右子树
q->deep = max(depth(q->l), p->deep) + 1;
p = q;
}
void RR(node *&p)//右旋
{
node *q;
q = p->r;
p->r = q->l;
q->l = p;
p->deep = max(depth(p->l), depth(p->r)) + 1;
q->deep = max(p->deep, depth(q->r)) + 1;
p = q;
}
void LR(node *&p)//左右 应当先右右后左左
{
RR(p->l);
LL(p);
}
void RL(node *&p)//右左
{
LL(p->r);
RR(p);
}
void Insert(node *&p, int k)//建立
{
if(!p)
{
p = new node;
p->data = k;
p->l = p->r = NULL;
p->deep = 1;
}
else if(k < p->data)//在左子树上开始建立
{
Insert(p->l, k);
if(depth(p->l) - depth(p->r) > 1)
{
if(k < p->l->data)
LL(p);
else
LR(p);
}
}
else if(k > p->data)//在右子树上开始建立
{
Insert(p->r, k);
if(depth(p->r) - depth(p->l) > 1)
{
if(k > p->r->data)
RR(p);
else
RL(p);
}
}
p->deep = max(depth(p->l), depth(p->r)) + 1;
}
int main()
{
int n;
cin>>n;
root = NULL;
while(n--)
{
int x;
cin>>x;
Insert(root, x);
}
cout<<root->data<<endl;
return 0;
}