Problem Description
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output
输出平衡二叉树的树根。
Example Input
5 88 70 61 96 120
Example Output
70
code:
#include <bits/stdc++.h>
using namespace std;
struct node
{
int data, d; //d为平衡因子
struct node *l, *r;
};
int maxx(int x, int y)
{
int d;
d = x>y?x:y;
return d;
}
int deep(struct node *head) //求某结点的深度
{
if(head==NULL)
return -1;
else
return head->d;
}
struct node *LL(struct node *head) //右旋
{
struct node *p;
p=head->l;
head->l=p->r;
p->r=head;
p->d = maxx(deep(p->l), deep(p->r))+1;
head->d = maxx(deep(head->l), deep(head->r))+1;
return p;
}
struct node *RR(struct node *head) //左旋
{
struct node *p;
p=head->r;
head->r = p->l;
p->l = head;
p->d = maxx(deep(p->l), deep(p->r))+1;
head->d = maxx(deep(head->l), deep(head->r))+1;
return p;
}
struct node *LR(struct node *head) //先做左旋 再做右旋
{
head->l = RR(head->l);
return LL(head);
}
struct node *RL(struct node *head) //先做右旋 再做左旋
{
head->r = LL(head->r);
return RR(head);
}
struct node *create(struct node *head, int x)
{
if(head==NULL) //当该节点为空 说明为叶子 给该结点分配一个地址 将x值赋给该结点 节点左右孩子均为空 深度定义为0
{
head=new struct node();
head->data = x;
head->l = head->r = NULL;
head->d=0;
}
else //节点不为空的情况
{
if(x>head->data) //当x的值比节点的值大的时候, 往右子树赋值
{
head->r = create(head->r, x);
if(deep(head->r)-deep(head->l)>1) //判断是否平衡 不平衡时,根据x的值跟右子树的大小关系进行左旋或者先右旋再左旋;
{
if(x>head->r->data)
head = RR(head);
else
head = RL(head);
}
}
else if(x<head->data)
{
head->l = create(head->l, x);
if(deep(head->l)-deep(head->r)>1)
{
if(x<head->l->data)
head = LL(head);
else
head = LR(head);
}
}
}
head->d = maxx(deep(head->l), deep(head->r))+1;
return head;
};
int main()
{
int n;
while(~scanf("%d", &n))
{
struct node *head = NULL;
for(int i=1; i<=n; i++)
{
int m;
scanf("%d", &m);
head = create(head, m);
}
cout << head -> data << endl;
}
return 0;
}