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

来源:互联网 发布:vb.net 判断excel 启动 编辑:程序博客网 时间:2024/05/18 01:12

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

Time Limit: 400MS Memory Limit: 65536KB
Submit Statistic

Problem Description

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

Input

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

Output

输出平衡二叉树的树根。

Example Input

588 70 61 96 120

Example Output

70

Hint

 #include<bits/stdc++.h>
using namespace std;
struct node
{
    int data, h;
    node *l, *r;
};
int height(node *p)  //返回p的值
{
    if(p == NULL)
        return -1;
    return p->h;
}
node* LL(node *p)            //对LL型进行调整
{
    node *q;
    q = p->l;
    p->l = q->r;
    q->r = p;
    p->h = max(height(p->l),height(p->r)) + 1;
    q->h = max(height(q->l),(p->h)) + 1;
    return q;
}
node* RR(node *p)         //对RR型进行调整
{
    node *q;
    q = p->r;
    p->r = q->l;
    q->l = p;
    p->h = max(height(p->l),height(p->r)) + 1;
    q->h = max(height(q->l),(p->h)) + 1;
    return q;
}
node* LR(node *p)
{
    p->l = RR(p->l);
    return LL(p);
}
node* RL(node *p)
{
    p->r = LL(p->r);
    return RR(p);
}
node* f(int s, node *p)
{
    if(p == NULL)
    {
        p = new node;
        p->data = s;
        p->h = 0;
        p->l = p->r = NULL;
    }
    else if(s < p->data)
    {
        p->l = f(s,p->l);
        if(height(p->l)-height(p->r) == 2)
        {
            if(s<p->l->data)
                p = LL(p);
            else
                p = LR(p);
        }
    }
    else if(s > p->data)
    {
        p->r = f(s,p->r);
        if(height(p->l) - height(p->r) == -2)
        {
            if(s>p->r->data)
                p = RR(p);
            else
                p = RL(p);
        }
    }
    p->h = max(height(p->l),height(p->r)) + 1;
    return p;
}
int main()
{
    int n, x;
    while(cin>>n)
    {
        node *head = NULL;
        while(n--)
        {
            cin>>x;
            head = f(x,head);
        }
        cout<<head->data<<endl;
    }
    return 0;
}