E - Find the experimental data structure II: balanced binary tree

Description

The establishment of a balanced binary tree of a given input sequence, determine the establishment of balanced binary tree roots.
Input

Inputting a set of test data. The first line gives a positive integer data N (n <= 20), N represents the number of elements in the input sequence; line 2 gives the positive integer N, to establish a balanced binary tree data according to a given order.
Output

Output balanced binary tree roots.
Sample

Input

5
88 70 61 96 120
Output

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;
}
Published 177 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/Fusheng_Yizhao/article/details/104869610