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

题目描述
根据给定的输入序列建立一棵平衡二叉树,求出建立的平衡二叉树的树根。
输入
输入一组测试数据。数据的第1行给出一个正整数N(n <= 20),N表示输入序列的元素个数;第2行给出N个正整数,按数据给定顺序建立平衡二叉树。
输出
输出平衡二叉树的树根。
样例输入
5
88 70 61 96 120
样例输出
70


#include <stdio.h>
#include <stdlib.h>
struct node
{
    int date;
    int bf; //平衡因子
    struct node *lchild;
    struct node *rchild;
};
int max(int a,int b)//求最大值的函数
{
    int max;
    if(a>b)
        max=a;
    else
        max=b;
    return max;
}
int deep(struct node *root)//求深度
{
    if(root==NULL)
        return -1;
    else
        return root->bf;
}
struct node *LL(struct node *root)//右旋
{
    struct node *b;
    b=root->lchild;
    root->lchild=b->rchild;
    b->rchild=root;
    b->bf=max(deep(b->lchild),deep(b->rchild))+1;
    root->bf=max(deep(root->lchild),deep(root->rchild))+1;
    return b;
}
struct node *RR(struct node *root)//左旋
{
    struct node *b;
    b=root->rchild;
    root->rchild=b->lchild;
    b->lchild=root;
    b->bf=max(deep(b->lchild),deep(b->rchild))+1;
    root->bf=max(deep(root->lchild),deep(root->rchild))+1;
    return b;
}
struct node *LR(struct node *root)
{
    root->lchild=RR(root->lchild);
    return LL(root);
}
struct node *RL(struct node *root)
{
    root->rchild=LL(root->rchild);
    return RR(root);
}
struct node *creat(struct node *root,int s)
{
    if(root==NULL)
    {
        root=(struct node*)malloc(sizeof(struct node));
        root->date=s;
        root->bf=0;
        root->lchild=NULL;
        root->rchild=NULL;
    }
    else
    {
        if(s<root->date)
        {
            root->lchild=creat(root->lchild,s);
            if(deep(root->lchild)-deep(root->rchild)>1)
            {
                if(s<root->lchild->date)
                    root=LL(root);
                else
                    root=LR(root);
            }
        }
        else
        {
            root->rchild=creat(root->rchild,s);
            if(deep(root->rchild)-deep(root->lchild)>1)
            {
                if(s>root->rchild->date)
                    root=RR(root);
                else
                    root=RL(root);
            }
        }
    }
    root->bf=max(deep(root->lchild),deep(root->rchild))+1;
    return root;
}
int main()
{
    struct node *root;
    int i,n,s;
    scanf("%d",&n);
    root=NULL;
    for(i=1;i<=n;i++)
    {
        scanf("%d",&s);
        root=creat(root,s);
    }
    printf("%d\n",root->date);
    return 0;
}


/***************************************************
User name: jk180140刘洋
Result: Accepted
Take time: 0ms
Take Memory: 104KB
Submit time: 2018-12-22 20:53:34
****************************************************/```

猜你喜欢

转载自blog.csdn.net/qq_43588832/article/details/86523968
今日推荐