Problem Description
對應給定的一個序列可以唯一確定一棵二叉排序樹。然而,一棵給定的二叉排序樹卻可以由多種不同的序列得到。例如分別按照序列{3,1,4}和{3,4,1}插入初始爲空的二叉排序樹,都得到一樣的結果。你的任務書對於輸入的各種序列,判斷它們是否能生成一樣的二叉排序樹。
Input
輸入包含若干組測試數據。每組數據的第1行給出兩個正整數N (n < = 10)和L,分別是輸入序列的元素個數和需要比較的序列個數。第2行給出N個以空格分隔的正整數,作爲初始插入序列生成一顆二叉排序樹。隨後L行,每行給出N個元素,屬於L個需要檢查的序列。
簡單起見,我們保證每個插入序列都是1到N的一個排列。當讀到N爲0時,標誌輸入結束,這組數據不要處理。
Output
對每一組需要檢查的序列,如果其生成的二叉排序樹跟初始序列生成的二叉排序樹一樣,則輸出"Yes",否則輸出"No"。
Example Input
4 2
3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0Example Output
Yes
No
NoHint
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
using namespace std;
typedef struct node{
int data;
struct node *lchild,*rchild;
}Tree;
int len,len1;
Tree *creat(Tree *root,int x){ //創建樹
if(root==NULL){
root = new Tree();
root->data = x;
root->lchild = root->rchild =NULL;
}
else{
if(x<root->data)
root->lchild = creat(root->lchild,x);
else
root->rchild = creat(root->rchild,x);
}
return root;
}
int judge(Tree *root,Tree *root1){//判斷兩棵樹是否爲同一個二叉排序樹
if(root==NULL&&root1==NULL)
return 1;
else if(root!=NULL&&root1!=NULL){
if(root->data!=root1->data)
return 0;
else if(judge(root->lchild,root1->lchild)&&judge(root->rchild,root1->rchild))
return 1;
else
return 0;
}
else
return 0;
}
int main(){
int n,m,i;
int first[20],second[20];
while(scanf("%d",&n)!=EOF,n){
scanf("%d",&m);
for(i=1;i<=n;i++)
cin>>first[i];
Tree *root = new Tree();
root->data = first[1];
root->lchild = root->rchild=NULL;
for(i=2;i<=n;i++){
root = creat(root,first[i]);
}
while(m--){
for(i=1;i<=n;i++)
cin>>second[i];
Tree *root1 = new Tree();
root1->data = second[1];
root1->lchild=root1->rchild=NULL;
for(i=2;i<=n;i++){
root1=creat(root1,second[i]);
}
int key = judge(root,root1);
if(key==1)
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
}
return 0;
}