sdut原題鏈接 二叉排序樹 Time Limit: 1000MS Memory Limit: 65536KB
PRoblem Description 二叉排序樹的定義是:或者是一棵空樹,或者是具有下列性質的二叉樹: 若它的左子樹不空,則左子樹上所有結點的值均小于它的根結點的值; 若它的右子樹不空,則右子樹上所有結點的值均大于它的根結點的值; 它的左、右子樹也分別為二叉排序樹。 今天我們要判斷兩序列是否為同一二叉排序樹
Input 開始一個數n,(1<=n<=20) 表示有n個需要判斷,n= 0 的時候輸入結束。 接下去一行是一個序列,序列長度小于10,包含(0~9)的數字,沒有重復數字,根據這個序列可以構造出一顆二叉排序樹。 接下去的n行有n個序列,每個序列格式跟第一個序列一樣,請判斷這兩個序列是否能組成同一顆二叉排序樹。(數據保證不會有空樹)
Output
Example Input 2 123456789 987654321 432156789 0
Example Output NO NO
Hint
Author
以下為accepted代碼
#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct node{ char date; struct node *left; struct node *right;}BinTree;int flag;BinTree * Insert(BinTree *rt, char 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)///判斷兩個二叉搜索樹是否為空 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, i, len; char st1[24], st2[24]; while(scanf("%d", &n) != EOF && n) { BinTree *root = NULL; scanf("%s", st1); len = strlen(st1); for(i = 0; i < len; i++) { root = Insert(root, st1[i]);//調用二叉搜索樹的插入函數 } for(i = 0; i < n; i++) { scanf("%s", st2); BinTree *root1 = NULL; flag = 0; for(int j = 0; j < len; j++) { root1 = Insert(root1, st2[j]);//調用二叉搜索樹的插入函數 } judge(root, root1);//調用判斷兩個二叉搜索樹是否相同的函數 if(flag == len) printf("YES/n"); else printf("NO/n"); } } return 0;}/***************************************************User name: jk160630Result: AcceptedTake time: 0msTake Memory: 112KBSubmit time: 2017-02-08 16:41:37****************************************************/新聞熱點
疑難解答