-
题目描述:
-
判断两序列是否为同一二叉搜索树序列
-
输入:
-
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
-
输出:
-
如果序列相同则输出YES,否则输出NO
-
样例输入:
-
2 567432 543267 576342 0
-
样例输出:
-
YES NO
题目大意:判断两个序列是否属于同一棵二叉搜索树。方法是 根据这个序列构造出这棵二叉搜索树,然后根据先序遍历是否相同即可。注意这里不能用中序遍历 来判断,因为二叉排序树的中序遍历是相同的。
#include <iostream> #include <cstring> using namespace std; typedef struct node{ int key; struct node *lchild,*rchild; }Node,*BST; bool InsertBST(Node *&T,int element){ if(T == NULL){ T = new node; T->key = element; T->lchild = T->rchild = NULL; return true; } if(T->key > element){ return InsertBST(T->lchild, element); } else{ return InsertBST(T->rchild,element); } } void CreateBST(Node *&T,int a[],int n){ T = NULL; for(int i=0;i<n;i++){ InsertBST(T,a[i]); } } int b[10]; int k = 0; void PreorderBST(BST T){ if(T){ b[k] = T->key; k++; PreorderBST(T->lchild); PreorderBST(T->rchild); } } int main(){ int n; while(cin>>n){ if(n == 0) break; string str; cin>>str; BST Tree; int a[10]; for(int i=0;i<str.length();i++){ a[i] = str[i] - '0'; } CreateBST(Tree,a,str.length()); memset(b,0,sizeof(b)); k = 0; PreorderBST(Tree); int c[10]; for(int i=0;i<10;i++) c[i] = b[i]; string test_example; for(int i=0;i<n;i++){ cin>>test_example; for(int i=0;i<test_example.length();i++){ a[i] = test_example[i] - '0'; } CreateBST(Tree,a,test_example.length()); memset(b,0,sizeof(b)); k = 0; PreorderBST(Tree); bool flag = true; for(int i=0;i<10;i++){ if(b[i] != c[i]){ cout<<"NO"<<endl; flag = false; break; } } if(flag) cout<<"YES"<<endl; } } return 0; }