sdut原題鏈接 二叉排序樹 Time Limit: 1000MS Memory Limit: 65536KB
PRoblem Description 二叉排序樹的定義是:或者是一棵空樹,或者是具有下列性質(zhì)的二叉樹: 若它的左子樹不空,則左子樹上所有結(jié)點(diǎn)的值均小于它的根結(jié)點(diǎn)的值; 若它的右子樹不空,則右子樹上所有結(jié)點(diǎn)的值均大于它的根結(jié)點(diǎn)的值; 它的左、右子樹也分別為二叉排序樹。 今天我們要判斷兩序列是否為同一二叉排序樹
Input 開始一個(gè)數(shù)n,(1<=n<=20) 表示有n個(gè)需要判斷,n= 0 的時(shí)候輸入結(jié)束。 接下去一行是一個(gè)序列,序列長度小于10,包含(0~9)的數(shù)字,沒有重復(fù)數(shù)字,根據(jù)這個(gè)序列可以構(gòu)造出一顆二叉排序樹。 接下去的n行有n個(gè)序列,每個(gè)序列格式跟第一個(gè)序列一樣,請(qǐng)判斷這兩個(gè)序列是否能組成同一顆二叉排序樹。(數(shù)據(jù)保證不會(huì)有空樹)
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)//若原樹為空,生成并返回一個(gè)結(jié)點(diǎn)的二叉搜索樹 { 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)//判斷兩個(gè)二叉搜索樹是否相同{ if(rt1 == NULL || rt2 == NULL)///判斷兩個(gè)二叉搜索樹是否為空 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]);//調(diào)用二叉搜索樹的插入函數(shù) } 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]);//調(diào)用二叉搜索樹的插入函數(shù) } judge(root, root1);//調(diào)用判斷兩個(gè)二叉搜索樹是否相同的函數(shù) 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****************************************************/新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注