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

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

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 <bits/stdc++.h>
using namespace std;

typedef struct node{
    int data,length;
    struct node *l,*r;
}*tree;
int n,m,flag;

int length(tree root)
{
    if(root==NULL)
        return -1;
    else
        return root->length;
}

tree RR(tree root)
{
    struct node *temp = root->r;
    root->r = temp->l;
    temp->l = root;
    temp->length = max(length(temp->l),length(temp->r))+1;
    root->length = max(length(root->l),length(root->r))+1;
    return temp;
}
tree LL(tree root)
{

    node *temp = root->l;
    root->l = temp->r;
    temp->r = root;
    temp->length = max(length(temp->l),length(temp->r))+1;
    root->length = max(length(root->l),length(root->r))+1;
    return temp;
}
tree RL(tree root)
{
    root->r = LL(root->r);
    return RR(root);
}
tree LR(tree root)
{
    root->l = RR(root->l);
    return LL(root);
}

tree creat(int x,tree root)
{
    if(root==NULL)
    {
        root = new node;
        root->data = x;
        root->length =0;
        root->l = root->r = NULL;
    }
    else if(x>root->data)
    {
        root->r = creat(x,root->r);
        if(length(root->r)-length(root->l)>1)
        {
            if(root->r->data<x)
                root = RR(root);
            else
                root = RL(root);
        }
    }
    else if(x<root->data)
    {
        root->l = creat(x,root->l);
        if(length(root->l)-length(root->r)>1)
        {
            if(root->l->data<x)
                root = LR(root);
            else
                root = LL(root);
        }
    }
    root->length = max(length(root->l),length(root->r))+1;
    return root;
}

int main()
{
    int x;
    cin>>n;
    struct node *root = NULL;
    for(int i =0; i<n; i++)
    {
        cin >> x;
        root = creat(x,root);
    }
    cout << root->data <<endl;;
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值