平衡二叉树

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

Time Limit: 400 ms Memory Limit: 65536 KiB
Problem Description

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

Input

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

Output

输出平衡二叉树的树根。

Sample Input
5
88 70 61 96 120
Sample Output

70

#include <bits/stdc++.h>
using namespace std;
struct node
{
    int data;
    int h;
    struct node *l, *r;
};
struct node *LL(struct node *tree);
struct node *RR(struct node *tree);
struct node *LR(struct node *tree);
struct node *RL(struct node *tree);
int geth(struct node *tree);
struct node *insert_tree(int x, struct node *tree);
int main()        //——————————————————————————主函数起始
{
    int n, a;
    cin>>n;
    struct node *root =NULL;
    for(int i=0; i<n; i++)
    {
        cin>>a;
        root=insert_tree(a, root);//调用插入函数
    }
    cout<<root->data<<endl;
    return 0;
}                  //——————————————————————————主函数结束
struct node *LL(struct node *tree)
{
    struct node *p=tree->l;
    tree->l=p->r;
    p->r=tree;
    p->h=max(geth(p->l), tree->h)+1;
    tree->h=max(geth(tree->l), geth(tree->r))+1;
    return p;
}
struct node *RR(struct node *tree)
{
    struct node *p=tree->r;
    tree->r=p->l;
    p->l=tree;
    p->h=max(geth(p->l), tree->h)+1;
    tree->h=max(geth(tree->l), geth(tree->r))+1;
    return p;
}
struct node *LR(struct node *tree)
{
    tree->l=RR(tree->l);
    tree=LL(tree);
    return tree;
}
struct node *RL(struct node *tree)
{
    tree->r=LL(tree->r);
    tree=RR(tree);
    return tree;
}
int geth(struct node *tree)
{
    if(tree==NULL)
    {
        return -1;
    }
    else
        return tree->h;
}
struct node *insert_tree(int x, struct node *tree)//插入,建树
{
    if(tree==NULL)//如果根节点为空,直接存入数据
    {
        tree=new node;
        tree->data=x;
        tree->l=tree->r=NULL;
        tree->h=0;
    }
    else if(x>tree->data)//如果目标数据大,插入到根节点的右边
    {
        tree->r=insert_tree(x, tree->r);//递归调用插入函数
        if(geth(tree->r)-geth(tree->l)>1)//在插入结束后判断左右孩子的高度,如果失衡(高度差为大于1的数字),则需要进行旋转
        {
            if(x>tree->r->data)//首先,肯定是“R”开头的类型,如果根节点的右孩子的值小于目标数据,那么一定是插入了右孩子的右边,为RR类型
            {
                tree=RR(tree);
            }
            else//否则就是左边,为RL类型
                tree=RL(tree);
        }
    }
    else if(x<tree->data)
    {
        tree->l=insert_tree(x, tree->l);
        if(geth(tree->l)-geth(tree->r)>1)
        {
            if(x>tree->l->data)
            {
                tree=LR(tree);//比左孩子的数据大,为LR
            }
            else
                tree=LL(tree);//否则为LL
        }
    }
    tree->h=max(geth(tree->l), geth(tree->r))+1;//最后记得取一下根节点的高度
    return tree;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值