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

来源:互联网 发布:淘宝网店运营推广方案 编辑:程序博客网 时间:2024/06/05 12:58

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

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
#include<bits/stdc++.h>typedef struct node{    int data, d;    struct node *l, *r;}*Bitree;int max(int x, int y){    return x > y ? x : y;}int Deep(Bitree root){    if(root == NULL)        return -1;    else        return root->d;}Bitree LL(Bitree root){    Bitree p = root->l;    root->l = p->r;    p->r = root;    p->d = max(Deep(p->l), Deep(p->r))+1;    root->d = max(Deep(root->l), Deep(root->r))+1;    return p;}Bitree RR(Bitree root){    Bitree p = root->r;;    root->r = p->l;    p->l = root;    p->d = max(Deep(p->l), Deep(p->r))+1;    root->d = max(Deep(root->l), Deep(root->r))+1;    return p;}Bitree LR(Bitree root){    root->l = RR(root->l);    return LL(root);}Bitree RL(Bitree root){    root->r = LL(root->r);    return RR(root);}Bitree creat(Bitree root, int x){    if(root == NULL)    {        root = new node;        root->data = x;        root->d = 0;        root->l = root->r = NULL;    }    else if(root->data > x)    {        root->l = creat(root->l, x);        if(Deep(root->l) - Deep(root->r) > 1)        {            if(root->l->data > x)                root = LL(root);            else                root = LR(root);        }    }    else if(root->data < x)    {        root->r = creat(root->r, x);        if(Deep(root->r) - Deep(root->l) > 1)        {            if(root->r->data > x)                root = RL(root);            else                root = RR(root);        }    }    root->d = max(Deep(root->l), Deep(root->r))+1;    return root;}int main(){    int n, m;    scanf("%d", &n);    Bitree root = NULL;    while(n--)    {        scanf("%d", &m);        root = creat(root, m);    }    printf("%d\n", root->data);    return 0;}


阅读全文
0 0