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"。
Sample Input
4 2 3 1 4 2 3 4 1 2 3 2 4 1 2 1 2 1 1 2 0
Sample Output
Yes No No
Hint
Source
xam
代碼如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node *Tree; //定義排序樹
struct node
{
int data ;
struct node *left ;
struct node *right;
};
Tree creat(Tree t , int x)
{
if(t == NULL)
{
t = (Tree)malloc(sizeof(struct node)) ;
t->data = x;
t->left = NULL ;
t->right = NULL ;
}
else
{
if(x>t->data)
{
t->right = creat(t->right,x) ;
}
else if(x<t->data)
{
t->left = creat(t->left,x) ;
}
}
return t;
}
int isTree(Tree t1, Tree t2)
{
if(t1 == NULL && t2 == NULL )
return 1 ;
if((t1 == NULL && t2!=NULL)||(t2 == NULL && t1!=NULL))
return 0 ;
if(t1->data == t2->data)
{
return isTree(t1->left,t2->left)&&isTree(t1->right,t2->right) ;
}
else return 0 ;
}
int main()
{
int n , l ;
while(~scanf("%d",&n)){
if(n == 0)
break ;
scanf("%d",&l) ;
Tree t1 ; //定義起始樹
t1 = NULL ; //初始化爲空
int i ;
int x ;
//構建初始的排序樹
for(i = 0 ; i<n ;i++)
{
scanf("%d",&x) ;
t1 = creat(t1,x) ;
}
while(l--)
{
Tree t2 = NULL ;
for( i= 0 ; i<n ; i++)
{
scanf("%d",&x) ;
t2 = creat(t2,x) ;
}
if(isTree(t1,t2))
{
printf("Yes\n") ;
}
else printf("No\n") ;
}
}
return 0 ;
}