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

来源:互联网 发布:贝斯内录用什么软件 编辑:程序博客网 时间:2024/06/08 01:05

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

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
#include <stdio.h>#include <stdlib.h>#include <string.h>struct jian{    int a;    struct jian *lc,*rc;    int hight;};int max(int a,int b){    return a>b?a:b;}int depth(struct jian *t){    if(t==NULL)        return -1;    else        return t->hight;}struct jian *LL(struct jian *t){    struct jian *q;    q=t->lc;    t->lc=q->rc;    q->rc=t;    t->hight=max(depth(t->lc),depth(t->rc))+1;    return q;}struct jian *RR(struct jian *t){    struct jian *q;    q=t->rc;    t->rc=q->lc;    q->lc=t;    t->hight=max(depth(t->lc),depth(t->rc))+1;    return q;}struct jian *LR(struct jian *t){    t->lc=RR(t->lc);    return LL(t);}struct jian *RL(struct jian *t){    t->rc=LL(t->rc);    return RR(t);}struct jian *creat(struct jian *t,int c){    if(t==NULL)    {        t=(struct jian*)malloc(sizeof(struct jian));        t->a=c;        t->lc=t->rc=NULL;        t->hight=0;    }    else if(c<t->a)    {            t->lc=creat(t->lc,c);            if(depth(t->lc)-depth(t->rc)>1)            {                if((t->lc->a>c))                    t=LL(t);                else                    t=LR(t);            }    }    else if(c>t->a)    {        t->rc=creat(t->rc,c);        if(depth(t->rc)-depth(t->lc)>1)        {            if(c>t->rc->a)                t=RR(t);            else                t=RL(t);        }    }    t->hight=max(depth(t->lc),depth(t->rc))+1;    return t;}int main(){    int n,i;    int b[1200];    scanf("%d",&n);    struct jian *t=NULL;    for(i=0;i<n;i++)    {        scanf("%d",&b[i]);        t=creat(t,b[i]);    }    printf("%d\n",t->a);    return 0;}

Example Output

70


0 0
原创粉丝点击