7-4 是否同一棵二叉搜索樹

給定一個插入序列就可以唯一確定一棵二叉搜索樹。然而,一棵給定的二叉搜索樹卻可以由多種不同的插入序列得到。例如分別按照序列{2, 1, 3}和{2, 3, 1}插入初始爲空的二叉搜索樹,都得到一樣的結果。於是對於輸入的各種插入序列,你需要判斷它們是否能生成一樣的二叉搜索樹。

輸入格式:

輸入包含若干組測試數據。每組數據的第1行給出兩個正整數NNN (≤10\le 1010)和LLL,分別是每個序列插入元素的個數和需要檢查的序列個數。第2行給出NNN個以空格分隔的正整數,作爲初始插入序列。最後LLL行,每行給出NNN個插入的元素,屬於LLL個需要檢查的序列。

簡單起見,我們保證每個插入序列都是1到NNN的一個排列。當讀到NNN爲0時,標誌輸入結束,這組數據不要處理。

輸出格式:

對每一組需要檢查的序列,如果其生成的二叉搜索樹跟對應的初始序列生成的一樣,輸出“Yes”,否則輸出“No”。

輸入樣例:

4 2
3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0

輸出樣例:

Yes
No
No

參考代碼:

#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct Node *PNode;
struct Node{
    ElementType Data;
    PNode Left;
    PNode Right;
};
typedef PNode Tree;
/*結果並不是檢查完成就輸出,而是鍵入結束標誌後一起輸出
因此存在一個存儲結果以便最後一起輸出的過程*/
typedef struct RNode *PRNode;
struct RNode{
    bool a;
    PRNode next;
};//這是存結果的鏈表
//初始化結果鏈表頭、尾(定義全局變量)
PRNode tail = (PRNode)malloc(sizeof(struct RNode));
PRNode head = tail;
PRNode temp;
bool CheckSame(Tree Ti, Tree Tc);

Tree InsertTree(Tree T, ElementType a)
{
    if (!T){
        T = (PNode)malloc(sizeof(struct Node));
        T->Data = a;
        T->Left = T->Right = NULL;
    }
    else if (a > T->Data)
        T->Right = InsertTree(T->Right, a);//遞歸插入右子樹
    else
        T->Left = InsertTree(T->Left, a);//遞歸插入左子樹
    return T;
}

int BuildTree(int N, int L)
{
    Tree Ti = NULL;//初始樹的初始化
    ElementType a;
    for (int i = 0; i < N; i++){
        scanf("%d", &a);
        Ti = InsertTree(Ti, a);
    }//初始樹插入完成
    for ( ; L > 0; L--){
        Tree Tc = NULL;
        ElementType b;
        for (int j = 0; j < N; j++){
            scanf("%d", &b);
            Tc = InsertTree(Tc, b);//得到待比較的樹Tc
        }
        temp = (PRNode)malloc(sizeof(struct RNode));
        temp->a = CheckSame(Ti, Tc);
        temp->next = NULL;
        tail->next = temp;
        tail = temp;//將比較結果存入結果鏈表中
        //free(temp);
    }
    scanf("%d", &N);

    return N;
}

bool CheckSame(Tree Ti, Tree Tc)
{
    if (Ti == NULL && Tc == NULL)
        return true;
    if ((Ti == NULL && Tc != NULL) || (Ti != NULL && Tc == NULL))
        return false;
    if (Ti->Data != Tc->Data)
        return false;
    if (Ti->Left && Ti->Left)
        return CheckSame(Ti->Left, Tc->Left);
    else if (Ti->Left == NULL && Tc->Left == NULL)
        return CheckSame(Ti->Right, Tc->Right);
    else
        return false;
}

int main(int argc, char const *argv[])
{
    int N, L;
    scanf("%d ", &N);
    int flag = 0;
    while (N){
        scanf("%d\n", &L);
        N = BuildTree(N, L);
        flag = 1;
    }
    //遍歷結果鏈表即可
    if (!flag)
        return 0;
    else{
        head = head->next;
        while (head){
            if (head->a)
                printf("Yes\n");
            else
                printf("No\n");
            head = head->next;
        }
    }
    system("pause");
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章