特别的二叉排序树

来源:互联网 发布:wap 网站源码 编辑:程序博客网 时间:2024/04/27 05:40

问题 D: 特别的二叉排序树
时间限制: 1 Sec 内存限制: 128 MB
提交: 190 解决: 57
[提交][状态][讨论版]
题目描述
有一棵特别的二叉排序树,每个结点拥有一个数据值,且各结点的数据值互不相同,每个结点拥有一个权值,且各结点的权值也互不相同。每个结点的数据值均小于其左子结点的数据值,大于其右子结点的数据值。每个结点的权值均小于其子结点的权值。这种二叉排序树,当结点的数据值和权值已知时,树的形态将是唯一的,即相当于按权值顺序依次将结点插入树中所形成的二叉排序树。 请编写程序计算这棵树的深度,约定只有根结点的树的深度为1。
输入
输入的第一行为一个整数M,为测试用例的个数,0<M≤100。 输入的第二行开始为M个测试用例。 每个测试用例的第一行为一个整数N,表示树中结点的个数,0<N≤100。 测试用例的第二行为N个用空格隔开的整数,为结点上的数据值。 测试用例的第三行为N个用空格隔开的整数,为结点上的权值,结点顺序与上一行一致。
输出
对每个测试用例,输出树的深度,每个测试用例的输出占一行。
样例输入

133 2 12 1 3

样例输出

2
#include<stdio.h>#include<malloc.h>#include<stdlib.h>#define MAXSIZE 1000typedef struct BiTNode{    int data;      struct BiTNode *lchild,*rchild;}BiTNode,*BiTree;BiTree p;typedef struct SqList{    int r[3][MAXSIZE+1];    int length;}SqList;int Partition(SqList *L,int low,int high){    int pivotkey;    L->r[1][0]=L->r[1][low];    L->r[2][0]=L->r[2][low];    pivotkey=L->r[2][low];    while(low<high)    {        while(low<high&&L->r[2][high]>=pivotkey)            --high;        L->r[2][low]=L->r[2][high];        L->r[1][low]=L->r[1][high];        while(low<high&&L->r[2][low]<=pivotkey)            ++low;        L->r[2][high]=L->r[2][low];        L->r[1][high]=L->r[1][low];    }    L->r[2][low]=L->r[2][0];    L->r[1][low]=L->r[1][0];    return low;}void QSort(SqList *L,int low,int high){   int pivotloc;   if(low<high)   {       pivotloc=Partition(L,low,high);       QSort(L,low,pivotloc-1);       QSort(L,pivotloc+1,high);   }}void QuickSort(SqList *L){    QSort(L,1,L->length);}int TreeDeep(BiTree T){    int high=0;    if(T)    {        int lchilddeep=TreeDeep(T->lchild);        int rchilddeep=TreeDeep(T->rchild);        if(lchilddeep>=rchilddeep)            high=lchilddeep+1;        else            high=rchilddeep+1;    }    return high;}int insert(BiTree *T,int e){    if(*T==NULL)    {        (*T)=(BiTree)malloc(sizeof(BiTNode));        (*T)->data=e;        (*T)->lchild=(*T)->rchild=NULL;    return 1;    }    if(e==(*T)->data)        return 0;    else if(e<(*T)->data)        return insert(&(*T)->rchild,e);    else        return insert(&(*T)->lchild,e);}void CreateBiTree(BiTree *T,int *b,int n){    int i=0;    (*T)=NULL;    for(i=1;i<=n;i++)        insert(T,b[i]);}int main(){    int i,j,k,m,h,s,x;    int b[100];    SqList L;    scanf("%d",&m);    for(i=1;i<=m;i++)    {        scanf("%d",&L.length);        for(j=1;j<=2;j++)            for(h=1;h<=L.length;h++)              scanf("%d",&L.r[j][h]);        QuickSort(&L);        for(x=1;x<=L.length;x++)            b[x]=L.r[1][x];        CreateBiTree(&p,b,L.length);        s=TreeDeep(p);        printf("%d\n",s);    }    return 0;}

运行截图

原创粉丝点击