題意:給定含有n個元素的序列可建出相應的二叉搜索樹, 以及給出m個查詢序列,問這些待查詢序列的二叉搜索樹是否和最初的二叉搜索樹相同。測試樣例以0結束
tip:建樹+遍歷對比
#include<iostream>
using namespace std;
struct node {
int val;
struct node *l,*r;
};
struct node* create(struct node* root,int val) {
if(root==NULL) {
root=new node();
root->val=val;
root->l=root->r=NULL;
} else if(root->val>=val)
root->l=create(root->l,val);
else root->r=create(root->r,val);
return root;
}
bool checked(struct node* root,struct node* temp) {
if(root==NULL&&temp==NULL)
return true;
else if(root->val==temp->val)
return checked(root->l,temp->l)&&checked(root->r,temp->r);
else return false;
}
int main() {
int n,m;
cin>>n;
while(n) {
cin>>m;
struct node* root=NULL;
for(int i=0; i<n; ++i) {
int t;
cin>>t;
root=create(root,t);
}
for(int i=0; i<m; ++i) {
struct node* temp=NULL;
for(int j=0; j<n; ++j) {
int t;
cin>>t;
temp=create(temp,t);
}
if(checked(root,temp))
cout<<"Yes\n";
else cout<<"No\n";
}
cin>>n;
}
return 0;
}