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

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

Time Limit: 400 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

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

Input

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

Output

输出平衡二叉树的树根。

Sample Input

5
88 70 61 96 120

Sample Output

70
#include<iostream>

using namespace std;

struct bitree
{
    int data;
    int dep;
    struct bitree *lc;
    struct bitree *rc;
};
int Max(int x,int y)
{
    return x>y?x:y;
}
int depth(bitree *rt)
{
    if(!rt)
        return -1;
    return rt->dep;
}
bitree *LL(bitree *rt)
{
    bitree *p = rt->lc;
    rt->lc = p->rc;
    p->rc = rt;
    p->dep = Max(depth(p->lc),depth(p->rc))+1;
    rt->dep = Max(depth(rt->lc),depth(rt->rc))+1;
    return p;
};
bitree *RR(bitree *rt)
{
    bitree *p = rt->rc;
    rt->rc = p->lc;
    p->lc = rt;
    p->dep = Max(depth(p->lc),depth(p->rc))+1;
    rt->dep = Max(depth(rt->lc),depth(rt->rc))+1;
    return p;
};
bitree *RL(bitree *rt)
{
    rt->rc=LL(rt->rc);
    return RR(rt);
};
bitree *LR(bitree *rt)
{
    rt->lc=RR(rt->lc);
    return LL(rt);
};
bitree *Insert(bitree *rt,int x)
{
    if(!rt)
    {
        rt = new bitree;
        rt->lc = NULL;
        rt->rc = NULL;
        rt->dep = 1;
        rt->data = x;
    }
    else if(x<rt->data)
    {
        rt->lc = Insert(rt->lc,x);
        if(depth(rt->lc)-depth(rt->rc)>1)
        {
            if(x<rt->lc->data)
                rt=LL(rt);
            else
                rt=LR(rt);
        }
    }
    else if(x>rt->data)
    {
        rt->rc = Insert(rt->rc,x);
        if(depth(rt->rc)-depth(rt->lc)>1)
        {
            if(x>rt->rc->data)
                rt=RR(rt);
            else
                rt=RL(rt);
        }
    }
    rt->dep  = Max(depth(rt->lc),depth(rt->rc))+1;
    return rt;
};
int main()
{
    int i, n, x;
    bitree *root = NULL;
    cin>>n;
    for(i=0; i<n; i++)
    {
        cin>>x;
        root = Insert(root,x);
    }
    cout<<root->data<<endl;
}

 

posted @ 2018-12-17 17:27  葫芦锤  阅读(16)  评论(0)    收藏  举报  来源