think: 1 判斷兩個二叉搜索樹是否相同的函數中注意判斷二叉搜索樹rt1和二叉搜索樹rt2是否為空
sdut原題鏈接
數據結構實驗之查找一:二叉排序樹 Time Limit: 400MS Memory Limit: 65536KB
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 0
Example Output Yes No No
Hint
Author xam
以下為accepted代碼
#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct node{ int date; struct node *left; struct node *right;}BinTree;BinTree *root = NULL;int flag;BinTree * Insert(BinTree *rt, int x)//二叉搜索樹的插入算法{ if(!rt){/* 若原樹為空,生成并返回一個結點的二叉搜索樹*/ rt = (BinTree *)malloc(sizeof(BinTree)); rt->date = x; rt->left = rt->right = NULL; } else/* 開始找要插入元素的位置*/ { if(x < rt->date) { rt->left = Insert(rt->left, x);//遞歸插入左子樹 } else if(x > rt->date) { rt->right = Insert(rt->right, x);//遞歸插入右子樹 } } return rt;}void judge(BinTree *rt1, BinTree *rt2)//判斷兩個二叉搜索樹是否相同{ if(rt1 == NULL || rt2 == NULL)///判斷二叉搜索樹rt1和二叉搜索樹rt2是否為空 return; if(rt1 && rt2) { if(rt1->date != rt2->date) return; else { flag++; judge(rt1->left, rt2->left); judge(rt1->right, rt2->right); } }}int main(){ int n, m, i, x; while(scanf("%d", &n) != EOF && n) { scanf("%d", &m); for(i = 0; i < n; i++) { scanf("%d", &x); root = Insert(root, x);//調用二叉搜索樹的插入算法 } while(m--) { BinTree *root1 = NULL; for(i = 0; i < n; i++) { scanf("%d", &x); root1 = Insert(root1, x);//調用二叉搜索樹的插入算法 } flag = 0;///初始化 judge(root, root1); if(flag == n) printf("Yes/n"); else printf("No/n"); } } return 0;}/***************************************************User name: jk160630Result: AcceptedTake time: 0msTake Memory: 104KBSubmit time: 2017-02-08 14:50:32****************************************************/新聞熱點
疑難解答