当前位置: 代码迷 >> 综合 >> 二叉搜索树 HDU - 3791
  详细解决方案

二叉搜索树 HDU - 3791

热度:30   发布时间:2024-01-20 21:47:31.0

二叉搜索树

Problem Description

判断两序列是否为同一二叉搜索树序列

Input

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

Output

如果序列相同则输出YES,否则输出NO

Sample Input

2
567432
543267
576342
0

Sample Output

YES
NO

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{int data;  //数据域struct node *lchild,*rchild;  //左右子树
};
typedef struct node* Bit;
Bit inserttree(Bit t,int ch)
{if(t==NULL){ t= (struct node*)malloc(sizeof(struct node));t->data=ch;t->lchild=NULL;t->rchild=NULL;   }else if(ch>t->data)t->rchild=inserttree(t->rchild,ch);else t->lchild=inserttree(t->lchild,ch);return t;
} 
int flag=0;
void  check(Bit at,Bit bt)
{ if(flag==1)return;if(at==NULL||bt==NULL)return; if(at->data!=bt->data)flag=1; else{check(at->lchild,bt->lchild);check(at->rchild,bt->rchild);}return ;
}
int main()
{int n;char a[12],b[12];while(scanf("%d",&n)&&n){scanf("%s",a);Bit at=NULL;for(int i=0;i<strlen(a);i++){ at=inserttree(at,a[i]-'0');}while(n--){flag=0; scanf("%s",b); if(strlen(a)!=strlen(b))  //长度不同,一定不同{printf("NO\n");continue;}Bit bt=NULL; for(int i=0;i<strlen(b);i++){ bt=inserttree(bt,b[i]-'0');} check(at,bt);if(flag==1){printf("NO\n");}else{printf("YES\n");}}	}return 0;
}