二叉排序树
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 <iostream> #include <algorithm> #include<cstring> using namespace std; typedef struct node { int data; struct node *lchild,*rchild; } node, *tree; int f,j; int creat(tree &t,int n); int compare(tree t1,tree t2); void PreOrder(tree T,char *r); int main() { int a,l1,l2; tree t1=NULL,t2=NULL;//注意必须初始化,否则creat函数中if(null)无法执行 char s[20],t[20],r1[20],r2[20]; while(cin>>a) { if(a==0) break; t1=NULL; cin>>s; l1=strlen(s); for(int i=0; i<l1; i++) { creat(t1,s[i]);//char型放入Int中是Ascii码0是48 } j=0; PreOrder(t1,r1); r1[j]='\0'; //注意,必须要加!!!!! while(a--) { t2=NULL; cin>>t; l2=strlen(t); if(l1!=l2) { cout<<"NO\n"; break; } else { for(int i=0; i<l2; i++) { creat(t2,t[i]); } j=0; PreOrder(t2,r2); r2[j]='\0'; if(strcmp(r1,r2)==0) cout<<"YES\n"; else cout<<"NO\n"; } } } } int creat(tree &t,int n) { if(t==NULL)//当节点为空时,才新建节点 { t=(tree)malloc(sizeof(node)); if(!t) exit(0); t->lchild=NULL; t->rchild=NULL; t->data=n; //cout<<t->data<<endl; } else { if(n==t->data) return 0; else if(n>t->data) creat(t->rchild,n); else creat(t->lchild,n); } } int compare(tree t1,tree t2) { if(!t1&&!t2) return 1; else if(t1&&t2) { if(t1->data!=t2->data) { f=1; return 1; } compare(t1->lchild,t2->lchild); compare(t1->rchild,t2->rchild); } } void PreOrder(tree T,char *r) { if(T != NULL) { r[j++]=T->data; PreOrder(T->lchild,r); PreOrder(T->rchild,r); } }