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<stdlib.h>
#include<string.h>
typedef struct node
{
int data;
struct node* lchild;
struct node* rchild;
} tree;
tree* Build(tree* t, int key)
{
if (t == NULL)
{
t = (tree*)malloc(sizeof(tree));
t->data = key;
t->lchild = NULL;
t->rchild = NULL;
}
else
{
if (key < t->data)
t->lchild = Build(t->lchild, key);
else
t->rchild = Build(t->rchild, key);
}
return t;
}
int Judge(tree* t1, tree* t2)
{
if (t1 == NULL && t2 == NULL)
{
return 1;
}
if ((t1 == NULL && t2 != NULL)||(t1 != NULL &&t2 == NULL))
{
return 0;
}
if (t1->data == t2->data)
{
return Judge(t1->lchild, t2->lchild)&&Judge(t1->rchild, t2->rchild);
}
else
{
return 0;
}
}
int main()
{
int n, m, num;
tree* t = NULL;
tree* r = NULL;
while(scanf("%d", &n) != EOF && n)
{
t = NULL;
scanf("%d", &m);
for (int i = 0; i < n; i++)
{
scanf("%d", &num);
t = Build(t, num);
}
for (int i = 0; i < m; i++)
{
r = NULL;
for (int j = 0; j < n; j++)
{
scanf("%d", &num);
r = Build(r, num);
}
if (Judge(t, r))
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
}
return 0;
}