Descripción
El establecimiento de un árbol binario equilibrado de una secuencia de entrada dado, determinar el establecimiento de raíces de los árboles binarios equilibrado.
entrada
Introducción de un conjunto de datos de prueba. La primera línea da un número entero positivo de datos N (n <= 20), N representa el número de elementos en la secuencia de entrada; línea 2 da el número entero positivo de N, para establecer un conjunto de datos de árbol binario equilibrado de acuerdo con un orden dado.
salida
Salida balanceada raíces de los árboles binarios.
muestra
Entrada
5
88 70 61 96 120
de salida
70
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
//#define MAX 1000
typedef int TelemType;
typedef struct node
{
TelemType data;
int deep;
struct node* l,*r;
}node;
int max(int x,int y)//判断大小
{
return x > y ? x: y;
}
int Deep(struct node*head)//判断左右子树的深度,从而判断需不需要继续旋转
{
int d=0;
if(head)
{
int l1 = Deep(head->l);
int l2 = Deep(head->r);
if(l1>=l2)
d = 1+l1;
else
d= 1+l2;
}
return d;
}
struct node *LL(struct node*head)//右转
{
struct node*p;
p = head->l;
head->l = p->r;
p->r = head;
p->deep = max(Deep(p->l),Deep(p->r))+1;
head->deep = max(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->deep = max(Deep(p->l),Deep(p->r))+1;
head->deep = max(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 *creat(struct node*head,int m)
{
if(head == NULL)
{
head = (struct node*)malloc(sizeof(struct node));
head ->l = NULL;
head ->r = NULL;
head ->data = m;
head ->deep = 0;
}
else
{
if(m < head->data)
{
head -> l = creat(head->l,m);
if(Deep(head->l) - Deep(head->r)>1)
{
if(head->l->data>m)
return LL(head);
else
return LR(head);
}
}
else
{
head->r = creat(head->r,m);
if(Deep(head->r)-Deep(head->l)>1)
{
if(head->r->data < m)
return RR(head);
else
return RL(head);
}
}
}
head ->deep = max(Deep(head->l),Deep(head->r))+1;
return head;
};
int main()
{
int n,m,i;
scanf("%d",&n);
struct node*head = NULL;
for(i=0;i<n;i++)
{
scanf("%d",&m);
head = creat(head,m);
}
printf("%d\n",head->data);
return 0;
}