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

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

Time Limit: 400MS Memory limit: 65536K

题目描述

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

输入

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

输出

输出平衡二叉树的树根。

示例输入

5
88 70 61 96 120

示例输出

70

#include 

using namespace std;

struct node
{
    int data;
    int h;
    node *l, *r;
};
int Deep(node *head)
{
    if(!head)
        return -1;
    return head->h;
}

node *Left(node *head)
{
    node *q = head->l;
    head->l = q->r;
    q->r = head;
    q->h = max(Deep(q->l),Deep(q->r))+1;
    head->h = max(Deep(head->l),Deep(head->r))+1;
    return q;
}
node *Right(node *head)
{
    node *q = head->r;
    head->r = q->l;
    q->r = head;
    q->h = max(Deep(q->l),Deep(q->r))+1;
    head->h = max(Deep(head->l),Deep(head->r))+1;
    return q;
}
node *LLeft(node *head)
{
    head->l = Right(head->l);
    return Left(head);
}

node *RRight(node *head)
{
    head->r = Left(head->r);
    return Right(head);
}

node *Inster(node *head, int x)
{
    if(!head)
    {
        head = new node;
        head->l = NULL, head->r = NULL;
        head->data = x;
        head->h = 0;
    }
    else if(x < head->data)
    {
        head->l = Inster(head->l, x);
        if(Deep(head->l) - Deep(head->r) > 1)
        {
            if(x < head->l->data)
                head = Left(head);
            else
                head = LLeft(head);
        }
    }
    else
    {
        head->r = Inster(head->r, x);
        if(Deep(head->r) - Deep(head->l) > 1)
        {
            if(x < head->r->data)
                head = RRight(head);
            else
                head = Right(head);
        }
    }
    head->h = max(Deep(head->l),Deep(head->r))+1;
    return head;
}

int main()
{
    int n, x;
    cin>>n;
    node *head = NULL;
    for(int i=0; i>x;
        head = Inster(head,x);
    }
    cout<data<



你可能感兴趣的:(ACM)