当前位置: 代码迷 >> 综合 >> 二叉排序树oj
  详细解决方案

二叉排序树oj

热度:72   发布时间:2024-01-14 23:03:53.0

二叉排序树

Time Limit: 1000MS Memory Limit: 65536KB
Problem Description

二叉排序树的定义是:或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。 今天我们要判断两序列是否为同一二叉排序树

Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉排序树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉排序树。(数据保证不会有空树)
Output
Example Input
2
123456789
987654321
432156789
0
Example Output
NO
NO
Hint
Author

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{int data;struct note *l,*r;
};
int aa[1010],bb[1010];
char a[10];
int k = 0;
struct node *creat(struct node *t,int x)
{if(t==NULL){t = (struct node *)malloc(sizeof(struct node));t->data = x;t->l=NULL;t->r=NULL;}else{if(x < t->data)t->l = creat(t->l,x);elset->r = creat(t->r,x);}return t;
}
void mid(struct node *t)
{if(t!=NULL){aa[k++] = t->data;mid(t->l);//aa[k++] = t->data;mid(t->r);}
}
void mid2(struct node *t)
{if(t!=NULL){bb[k++] = t->data;mid2(t->l);//bb[k++] = t->data;mid2(t->r);}
}
int main()
{int x,n,i,l;while(scanf("%d",&n) != EOF&&n){scanf("%s",a);l = strlen(a);struct node *root=NULL;for(i = 0;i < l;i++){x = a[i] - '0';root = creat(root,x);}k = 0;mid(root);while(n--){scanf("%s",a);l = strlen(a);root=NULL;for(i = 0;i < l;i++){x = a[i] - '0';root = creat(root,x);}k =0;mid2(root);//for(i = 0;i < l;i++)// {//      printf("%d %d\n",aa[i],bb[i]);//}for(i = 0;i < l;i++){if(aa[i] != bb[i]){printf("NO\n");break;}}if(i == l)printf("YES\n");}}return 0;
}