平衡二叉树

Problem Description

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

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

输出平衡二叉树的树根。
Sample Input

5
88 70 61 96 120

Sample Output

70

隔一段时间不看就忘QwQ,我能怎么办,我也没办法呀。这次绝对不会忘了

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cstdlib>

const int N = 1e5;

struct node
{
    int data;    //数据
    int height;  //高度
    struct node *lchild, *rchild;
    node(int x): data(x), height(1), lchild(0), rchild(0){} //构造器
};
//获取节点高度
int GetHeight(node *root)
{
    if(root == NULL) return 0;
    return root->height;
}
//获取节点的平衡因子
int GetBF(node *root)
{
    return GetHeight(root->lchild) - GetHeight(root->rchild);
}
//更新节点的高度
void UpdateHeight(node *root)
{
    root->height = std::max(GetHeight(root->lchild), GetHeight(root->rchild)) + 1;
}
//左旋
void L(node *&root)
{
    node *temp = root->rchild;
    root->rchild = temp->lchild;
    temp->lchild = root;
    UpdateHeight(root);
    UpdateHeight(temp);
    root = temp;
}
//右旋
void R(node *&root)
{
    node *temp = root->lchild;
    root->lchild = temp->rchild;
    temp->rchild = root;
    UpdateHeight(root);
    UpdateHeight(temp);
    root = temp;
}
//插入元素
void Insert(node *&root, int x)
{
    if(root == NULL)
    {
        root = new node(x);
        return;
    }
    if(x < root->data)
    {
        Insert(root->lchild, x);
        UpdateHeight(root);
        if(GetBF(root) == 2)
        {
            if(GetBF(root->lchild) == 1)
                R(root);
            else
            {
                L(root->lchild);
                R(root);
            }
        }
    }
    else
    {
        Insert(root->rchild, x);
        UpdateHeight(root);
        if(GetBF(root) == -2)
        {
            if(GetBF(root->rchild) == -1)
                L(root);
            else
            {
                R(root->rchild);
                L(root);
            }
        }
    }
}

int main()
{
    int n, m;
    node *root = NULL;
    scanf("%d", &n);
    while(n--)
    {
        scanf("%d", &m);
        Insert(root, m);
    }
    printf("%d", root->data);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值