二叉排序树
Time Limit: 1000MS Memory limit: 65536K
题目描述
二叉排序树的定义是:或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。 今天我们要判断两序列是否为同一二叉排序树
输入
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉排序树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉排序树。(数据保证不会有空树)
输出
示例输入
2 123456789 987654321 432156789 0
示例输出
NO NO#include <stdio.h> #include <stdlib.h> #include <string.h> char s[2][30]; char qian[2][30]; char hou[2][30]; int jin=0,qjin=0,hjin=0; int g=0; struct node { char data; struct node *rchild,*lchild; }; struct node *creat(struct node *toop,char k) { if(toop==NULL) { toop=(struct node *)malloc(sizeof(struct node)); toop->lchild=NULL; toop->rchild=NULL; toop->data = k; } else { if(k<toop->data) { toop->lchild=creat(toop->lchild,k); } else { toop->rchild=creat(toop->rchild,k); } } return toop; } void bianli(struct node *toop) { if(toop!=NULL) { qian[g][qjin++]=toop->data; bianli(toop->lchild); s[g][jin++]=toop->data; bianli(toop->rchild); hou[g][hjin++]=toop->data; } } int main() { int n; char st[30]; while(~scanf("%d",&n)&&n!=0) { g=0;jin=0;hjin=0;qjin=0; memset(qian,0,sizeof(qian)); scanf("%s",st); int len=strlen(st); struct node *toop; int i,j; toop=NULL; for(i=0; i<len; i++) { toop=creat(toop,st[i]); } bianli(toop); for(i=0; i<n; i++) { g=1;jin=0,hjin=0,qjin=0; scanf("%s",st); struct node *t; t=NULL; for(j=0; j<len; j++) { t=creat(t,st[j]); } bianli(t); if(strcmp(qian[0],qian[1])==0) { printf("YES\n"); } else { printf("NO\n"); } } } return 0; }