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

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

                                               Time Limit: 400MS Memory Limit: 65536KB
Problem Description

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

Input

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

Output

输出平衡二叉树的树根。

Example Input
5
88 70 61 96 120
Example Output
70

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct node
{
    int data;
    struct node *lc,*rc;
    int bf;
}Bitree;

int max1(int a,int b)
{
    return (a>b?a:b);
}

int deep(Bitree* tree)
{
    if(!tree)
    {
        return -1;
    }
    else
    {
        return tree->bf;
    }
}

Bitree* L_Rotate(Bitree* root) //左旋
{
    Bitree *p;
    p = root->rc;
    root->rc = p->lc;
    p->lc = root;
    p->bf = max1(deep(p->lc),deep(p->rc)) + 1;
    root->bf = max1(deep(root->lc),deep(root->rc)) + 1;
    return p;
}

Bitree* R_Rotate(Bitree* root) //右旋
{
    Bitree *p;
    p = root->lc;
    root->lc = p->rc;
    p->rc = root;
    p->bf = max1(deep(p->lc),deep(p->rc)) + 1;
    root->bf = max1(deep(root->lc),deep(root->rc)) + 1;
    return p;
}

Bitree* L_R_Rotate(Bitree* root) //先左旋再右旋
{
    root->lc = L_Rotate(root->lc);
    root = R_Rotate(root);
    return root;
}

Bitree* R_L_Rotate(Bitree* root) //先右旋再左旋
{
    root->rc = R_Rotate(root->rc);
    root = L_Rotate(root);
    return root;
}

Bitree* create(Bitree* root,int k)
{
    if(!root)
    {
        root = (Bitree *)malloc(sizeof(Bitree));
        root->data = k;
        root->rc = root->lc = NULL;
        root->bf = 0;
    }
    else
    {
        if(k < root->data)
        {
            root->lc = create(root->lc,k);
            if(deep(root->lc)-deep(root->rc) > 1)
            {
                if(k < root->lc->data)
                {
                    root = R_Rotate(root);
                }
                else
                {
                    root = L_R_Rotate(root);
                }
            }
        }
        else if(k > root->data)
        {
            root->rc = create(root->rc,k);
            if(deep(root->rc)-deep(root->lc) > 1)
            {
                if(k < root->rc->data)
                {
                    root = R_L_Rotate(root);
                }
                else
                {
                    root = L_Rotate(root);
                }
            }
        }
    }
    root->bf = max1(deep(root->lc),deep(root->rc)) + 1;
    return root;
}

int main()
{
    int n;
    int k;
    Bitree * root = NULL;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%d",&k);
        root = create(root,k);
    }
    printf("%d\n",root->data);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值