E - 数据结构实验之查找二:平衡二叉树

Description

根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
Input

输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
Output

输出平衡二叉树的树根。
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;
}
发布了177 篇原创文章 · 获赞 7 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Fusheng_Yizhao/article/details/104869610
今日推荐