二叉排序树(Binary Sort Tree)又称二叉查找树(Binary Search Tree),亦称二叉搜索树。 它或者是一棵空树;或者是具有下列性质的二叉树: (1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值; (2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值; (3)左、右子树也分别为二叉排序树;
对应HDU题目:点击打开链接
Description
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
2 567432 543267 576342 0
Sample Output
YES NO#include<cstdio> #include<cstdlib> #include<cmath> #include<map> #include<queue> #include<stack> #include<vector> #include<algorithm> #include<cstring> #include<string> #include<iostream> const int MAXN=50000+10; const int INF=1<<25; using namespace std; bool flag; typedef struct Node { char key; Node *left, *right; }node; void InsertBST(node *&p, char k) { if(p==NULL){ p=(node*)malloc(sizeof(node)); p->key=k; p->left=NULL; p->right=NULL; } else if(k<p->key) InsertBST(p->left, k); else InsertBST(p->right, k); } node *CreateBST(char a[], int n) { node *bt=NULL; int i=0; while(i<n) { InsertBST(bt, a[i]); i++; } return bt; } void cmp(node *p1, node *p2) { if(p1==NULL && p2==NULL){return;} if(p1==NULL || p2==NULL){flag=0; return;} if(p1->key!=p2->key){flag=0; return;} else{ cmp(p1->left, p2->left); cmp(p1->right, p2->right); } } void freedom(node *p) { if(p==NULL) return; freedom(p->left); freedom(p->right); free(p); } int main() { //freopen("in.txt","r",stdin); int n; while(scanf("%d", &n), n) { node *t; char s[15]; scanf("%s", s); t=CreateBST(s,strlen(s)); while(n--) { flag=1; scanf("%s", s); node *p; p=CreateBST(s,strlen(s)); cmp(t,p); if(flag) printf("YES\n"); else printf("NO\n"); freedom(p); } freedom(t); } return 0; }