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

本文介绍了一种平衡二叉树的实现方法,包括基本的数据结构定义、左右旋转操作及节点插入过程。通过这些操作确保了树的高度平衡,进而提高了搜索效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include <bits/stdc++.h>
typedef int Elemtype;


typedef struct BiTNode
{
    Elemtype data;
    int depth;
    struct BiTNode *lchild;
    struct BiTNode *rchild;
}BiTNode,*BiTree;




int max(int x,int y)  //找两个数中的较大值
{
    return x>y ? x:y;
}




int Deep(BiTree T) //求某棵树的深度
{
    if (!T)
        return 0;
    else return T->depth;
}




BiTree LL(BiTree T)//右旋
{
 BiTree p = T->lchild;
 T->lchild = p->rchild;
 p->rchild = T;
 p->depth = max(Deep(p->lchild),Deep(p->rchild))+1;
 T->depth = max(Deep(T->lchild),Deep(T->rchild))+1;
 return p                                                                                                                                                     ;
}




BiTree RR(BiTree T)//左旋
{
 BiTree p = T->rchild;
 T->rchild = p->lchild;
 p->lchild = T;
 p->depth = max(Deep(p->lchild),Deep(p->rchild))+1;
 T->depth = max(Deep(T->lchild),Deep(T->rchild))+1;
 return p;
}




BiTree LR(BiTree T)
{
  T->lchild = RR(T->lchild);//先做左旋
  return LL(T);//在做右旋
}




BiTree RL(BiTree T)
{
 T->rchild = LL(T->rchild);//先做右旋
 return RR(T);//在做左旋
}
BiTree Create(BiTree T,int x)
{
    if (T == NULL)
    {
        T = new(BiTNode);
        T->data = x;
        T->depth = 0;
        T->rchild = NULL;
        T->lchild = NULL;
    }
    else if (x < T->data )
    {
        T->lchild = Create(T->lchild,x);
        if (abs(Deep(T->lchild) - Deep(T->rchild)) > 1)
        {
            if (x < T->lchild->data)
                T = LL(T);
            else
                T = LR(T);
        }
    }
    else if (x > T->data)
    {
        T->rchild  = Create(T->rchild,x);
        if (abs(Deep(T->rchild) - Deep(T->lchild)) > 1)
        {
            if (T->rchild->data > x)
                T = RL(T);
            else
                T = RR(T);
        }
    }
    T->depth = max(Deep(T->lchild),Deep(T->rchild)) + 1;
    return T;
}




int main()
{
    int n,m;
    scanf ("%d",&n);
    BiTree T = NULL;
    for (int i=0; i<n; i++)
    {
        scanf ("%d",&m);
        T = Create(T,m);
    }
    printf ("%d\n",T->data);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值