题目描述
判断两序列是否为同一二叉搜索树序列
输入描述:
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。 接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。 接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
输出描述:
如果序列相同则输出YES,否则输出NO
示例1
输入
2 567432 543267 576342 0
输出
YES NO
#include<iostream>
#include<cstdio>
#include<string>
//前序遍历和中序遍历可以唯一确定一棵二叉树,
//而对二叉排序树而言,相同元素的二叉排序树中
//序遍历一定相同,而不同元素二叉排序树使用前
//序遍历就可以发现不相同,所以只需要前序遍历
//两个二叉树,比较一下就可以判断
using namespace std;
string pre,in;
struct TreeNode{
char data;
TreeNode* leftchild;
TreeNode* rightchild;
TreeNode(char c):data(c),leftchild(NULL),rightchild(NULL){}
};
TreeNode* Insert(TreeNode* root,char x){
if(root==NULL){
root=new TreeNode(x);
}
else if(x<root->data){
root->leftchild=Insert(root->leftchild,x);
}
else if(x>root->data){
root->rightchild=Insert(root->rightchild,x);
}
return root;
}
string preorder(TreeNode* root){
if(root==NULL) return "#";
return root->data+preorder(root->leftchild)+preorder(root->rightchild);
}
int main(){
int n;
while(cin>>n){
if(n==0) break;
string s; TreeNode* root=NULL;
cin>>s;
//构建初始的排序树
for(int i=0;i<s.size();i++){
root=Insert(root,s[i]);
}
string pre=preorder(root);
//构建用来比较的排序树
for(int i=0;i<n;i++){
string str; TreeNode* T=NULL;
cin>>str;
for(int j=0;j<str.size();j++){
T=Insert(T,str[j]);
}
string pre1=preorder(T);
//进行比较
if(pre1==pre) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
return 0;
}